SlideShare a Scribd company logo
1 of 41
Download to read offline
Programming RPi for
IoT Applications
Presented by
Dr Shobha K R
Past Chair IEEE Bangalore Section
Sensors Council Chapter
Senior IEEE member, LMISTE, MWIE,
MISOC,IAENG, Technical head of ISOC
Rural development SIG
Professor, Dept of TCE
Ramaiah Institute of Technology
Agenda
• Basics of Python
• RPI Basics
• RPI coding
Motivation to use Python
• Python language employs intuitive key-words, simpler
syntax – so easy to learn
• Python code is compact
• Python is supported on wider range of platforms – so
code is portable
• Wide library support
• Meets the end-to-end development needs of IoT
systems – for capturing sensor data, web services,
web applications, analytical components
Python
• Python is a general-purpose high level programming language and suitable for
providing a solid foundation to the reader in the area of cloud computing.
• The main characteristics of Python are:
• 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.
Python - Benefits
• Easy-to-learn, read and maintain
• Python is a minimalistic language with relatively few keywords, uses English keywords and has
fewer syntactical constructions as compared to other languages. Reading Python programs feels
like English with pseudo-code like constructs. Python is easy to learn yet an extremely powerful
language for a wide range of applications.
• Object and Procedure Oriented
• Python supports both procedure-oriented programming and object-oriented programming.
Procedure oriented paradigm allows programs to be written around procedures or functions that
allow reuse of code. Procedure oriented paradigm allows programs to be written around objects
that include both data and functionality.
• Extendable
• Python is an extendable language and allows integration of low-level modules written in languages
such as C/C++. This is useful when you want to speed up a critical portion of a program.
• Scalable
• Due to the minimalistic nature of Python, it provides a manageable structure for large programs.
• Portable
• Since Python is an interpreted language, programmers do not have to worry about compilation,
linking and loading of programs. Python programs can be directly executed from source
• Broad Library Support
• Python has a broad library support and works on various platforms such as Windows, Linux, Mac,
etc.
Python - Setup
• Windows
• 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
#Install 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 libbz2-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
Numbers
• 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.
#Integer
>>>a=5
>>>type(a)
<type ’int’>
#Floating Point
>>>b=2.5
>>>type(b)
<type ’float’>
#Long
>>>x=9898878787676L
>>>type(x)
<type ’long’>
#Complex
>>>y=2+5j
>>>y
(2+5j)
>>>type(y)
<type ’complex’>
>>>y.real
2
>>>y.imag
5
#Addition
>>>c=a+b
>>>c
7.5
>>>type(c)
<type ’float’>
#Subtraction
>>>d=a-b
>>>d
2.5
>>>type(d)
<type ’float’>
#Multiplication
>>>e=a*b
>>>e
12.5
>>>type(e)
<type ’float’>
#Division
>>>f=b/a
>>>f
0.5
>>>type(f)
<type float’>
#Power
>>>g=a**2
>>>g
25
Strings
• 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.
#Create string
>>>s="Hello World!"
>>>type(s)
<type ’str’>
#String concatenation
>>>t="This is sample program."
>>>r = s+t
>>>r
’Hello World!This is sample
program.’
#Get length of string
>>>len(s)
12
#Convert string to integer
>>>x="100"
>>>type(s)
<type ’str’>
>>>y=int(x)
>>>y
100
#Print string
>>>print s
Hello World!
#Formatting output
>>>print "The string (The
string (Hello World!) has 12
characters
#Convert to upper/lower
case
>>>s.upper()
’HELLO WORLD!’
>>>s.lower()
’hello world!’
#Accessing sub-strings
>>>s[0]
’H’
>>>s[6:]
’World!’
>>>s[6:-1]
’World’
#strip: Returns a copy of
the string with the
#leading and trailing
characters removed.
>>>s.strip("!")
’Hello World’
Lists
• Lists
• List 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.
#Create List
>>>fruits=[’apple’,’orange’,’ba
nana’,’mango’]
>>>type(fruits)
<type ’list’>
#Get Length of List
>>>len(fruits)
4
#Access List Elements
>>>fruits[1]
’orange’
>>>fruits[1:3]
[’orange’, ’banana’]
>>>fruits[1:]
[’orange’, ’banana’, ’mango’]
#Appending an item to a list
>>>fruits.append(’pear’)
>>>fruits
[’apple’, ’orange’, ’banana’,
’mango’, ’pear’]
#Removing an item from a list
>>>fruits.remove(’mango’)
>>>fruits
[’apple’, ’orange’, ’banana’,
’pear’]
#Inserting an item to a list
>>>fruits.insert(1,’mango’)
>>>fruits
[’apple’, ’mango’, ’orange’,
’banana’, ’pear’]
#Combining lists
>>>vegetables=[’potato’,’carrot’,’
onion’,’beans’,’radish’]
>>>vegetables
[’potato’, ’carrot’, ’onion’,
’beans’, ’radish’]
>>>eatables=fruits+vegetables
>>>eatables
[’apple’, ’mango’, ’orange’,
’banana’, ’pear’, ’potato’, ’carrot’,
’onion’, ’beans’, ’radish’]
#Mixed data types in a list
>>>mixed=[’data’,5,100.1,8287398L]
>>>type(mixed)
<type ’list’>
>>>type(mixed[0])
<type ’str’>
>>>type(mixed[1])
<type ’int’>
>>>type(mixed[2])
<type ’float’>
>>>type(mixed[3])
<type ’long’>
#Change individual elements of a list
>>>mixed[0]=mixed[0]+" items"
>>>mixed[1]=mixed[1]+1
>>>mixed[2]=mixed[2]+0.05
>>>mixed
[’data items’, 6,
100.14999999999999, 8287398L]
#Lists can be nested
>>>nested=[fruits,vegetables]
>>>nested
[[’apple’, ’mango’, ’orange’, ’banana’,
’pear’], [’potato’, ’carrot’, ’onion’,
’beans’, ’radish’]]
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.
#Create a Tuple
>>>fruits=("apple","mango","banana",
"pineapple")
>>>fruits
(’apple’, ’mango’, ’banana’, ’pineapple’)
>>>type(fruits)
<type ’tuple’>
#Get length of tuple
>>>len(fruits)
4
#Get an element from a tuple
>>>fruits[0]
’apple’
>>>fruits[:2]
(’apple’, ’mango’)
#Combining tuples
>>>vegetables=(’potato’,’carrot’,’onion’,’radis
h’)
>>>eatables=fruits+vegetables
>>>eatables
(’apple’, ’mango’, ’banana’, ’pineapple’,
’potato’, ’carrot’, ’onion’, ’radish’)
Dictionaries
• 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.
#Create a dictionary
>>>student={’name’:’Mary’,’id’:’8776’,’major’:’CS’
}
>>>student
{’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
>>>type(student)
<type ’dict’>
#Get length of a dictionary
>>>len(student)
3
#Get the value of a key in dictionary
>>>student[’name’]
’Mary’
#Get all items in a dictionary
>>>student.items()
[(’gender’, ’female’), (’major’, ’CS’), (’name’,
’Mary’), (’id’, ’8776’)]
#Get all keys in a dictionary
>>>student.keys()
[’gender’, ’major’, ’name’, ’id’]
#Get all values in a dictionary
>>>student.values()
[’female’, ’CS’, ’Mary’, ’8776’]
#Add new key-value pair
>>>student[’gender’]=’female’
>>>student
{’gender’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
#A value in a dictionary can be another dictionary
>>>student1={’name’:’David’,’id’:’9876’,’major’:’ECE’}
>>>students={’1’: student,’2’:student1}
>>>students
{’1’: {’gender’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’},
’2’: {’
major’: ’ECE’, ’name’: ’David’, ’id’: ’9876’}}
#Check if dictionary has a key
>>>student.has_key(’name’)
True
>>>student.has_key(’grade’)
False
Type Conversions
#Convert to string
>>>a=10000
>>>str(a)
’10000’
#Convert to int
>>>b="2013"
>>>int(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’])
• Type conversion examples
Control Flow – if statement
• The if statement in Python is similar to the if statement in other languages.
>>>a = 25**5
>>>if a>10000:
print "More"
else:
print "Less"
More
>>>s="Hello World"
>>>if "World" in s:
s=s+"!"
print s
Hello World!
>>>if a>10000:
if a<1000000:
print "Between 10k and
100k"
else:
print "More than 100k"
elif a==10000:
print "Equal to 10k"
else:
print "Less than 10k"
More than 100k
>>>student={’name’:’Mary’,’id’:’8776’}
>>>if not student.has_key(’major’):
student[’major’]=’CS’
>>>student
{’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
Control Flow – for statement
• 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.
#Looping over characters in a string
helloString = "Hello World"
for c in helloString:
print c
#Looping over keys in a dictionary
student = ’name’: ’Mary’, ’id’:
’8776’,’gender’: ’female’, ’major’: ’CS’
for key in student:
print "%s: %s" %
(key,student[key]
#Looping over items in a list
fruits=[’apple’,’orange’,’banana’,’mango’]
i=0
for item in fruits:
print "Fruit-%d: %s" % (i,item)
i=i+1
Control Flow – while statement
• The while statement in Python executes the statements within the while loop as
long as the while condition is true.
#Prints even numbers upto 100
>>> i = 0
>>> while i<=100:
if i%2 == 0:
print i
i = i+1
Control Flow – Range statement
• The range statement in Python generates a list of numbers in arithmetic progression.
#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]
#Generate a list of numbers from
0 – 9
>>>range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Write the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the
end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min()
functions to compute the maximum and minimum numbers after the loop completes
numlist = list()
while ( True ) :
inp = input('Enter a number: ')
if inp == 'done' :
break
value = float(inp)
numlist.append(value)
print(numlist)
print(max(numlist))
print(min(numlist))
Functions
• 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.
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))
Syntax
def functionname( parameters ):
“’function_docstring“’
function_suite
return [expression]
Functions - Default Arguments
• 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
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age = 50, name = "miki" )
printinfo( name = "miki" )
Output
Name: miki
Age 50
Name: miki
Age 35
Functions - Passing by Reference
• All parameters in the Python functions are passed by reference.
• If a parameter is changed within a function the change also reflected back in the calling
function.
# Function definition is here def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist) return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Output
Values inside the function before change: [10, 20, 30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
Functions - Passing by Reference
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]
# This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Output
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Functions - Keyword Arguments
• Functions can also be called using keyword arguments that identifies the arguments by the
parameter name when the function is called.
• This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters
def printStudentRecords(name,age=20,major=’CS’):
print( "Name: " , name)
print ("Age: " , age)
print ("Major: “ , major)
#This will give error as name is required argument
printStudentRecords()
Output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: printStudentRecords() takes at least 1 argument (0
given)
#Correct use
printStudentRecords(name=’Alex’)
Name: Alex
Age: 20
Major: CS
printStudentRecords(name=’Bob’,age=22,major=’ECE’)
Name: Bob
Age: 22
Major: ECE
printStudentRecords(name=’Alan’,major=’ECE’)
Name: Alan
Age: 20
Major: ECE
Functions - Variable Length Arguments
• Python functions can have variable length arguments. The variable length arguments are
passed to as a tuple to the function with an argument prefixed with asterix (*)
Output is: 10
Output is: 70 60 50
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
Modules
• Python allows organizing
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.
#student module - saved as student.py
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: " % (i))
print ("Name: " ,students[key]['name'])
print "Grade: " ,str(students[key]['grade'])
i = i+1
#Using student module
>>>import student
>>>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
>>>student.printRecords(students)
There are 5 students
Student-1:
Name: Bob
Grade: 2.5
Student-2:
Name: David
Grade: 4.2
Student-3:
Name: Mary
Grade: 3.5
Student-4:
Name: Alex
Grade: 3.8
Student-5:
Name: John
Grade: 4.1
>>>avg = student. averageGrade(students)
>>>print ("The average garde is: %0.2f" % (avg))
3.62
# Importing a specific function from
a module
>>>from student import
averageGrade
# Listing all names defines in a
module
>>>dir(student)
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.
• If the buffering value is set to 0, no buffering takes place. If the
buffering value is 1, line buffering is performed while accessing a
file. If you specify the buffering value as an integer greater than 1,
then buffering action is performed with the indicated buffer size
• After the file contents have been read the close function is called
which closes the file object.
# Example of reading line by line
>>>fp = open('file1.txt','r')
>>>print( "Line-1: " , fp.readline())
Line-1: Python supports more than one programming paradigms.
>>>print ("Line-2: " , fp.readline())
Line-2: Python is an interpreted language.
>>>fp.close()
# Example of reading an entire file
>>>fp = open('file.txt','r')
>>>content = fp.read()
>>>print content
This is a test file.
>>>fp.close()
# Example of reading lines in a loop
>>>fp = open(’file1.txt’,’r’)
>>>lines = fp.readlines()
>>>for line in lines:
print( line)
Python supports more than one programming paradigms.
Python is an interpreted language.
# Syntax for opening a file
file object = open(file_name [, access_mode][, buffering])
File Handling
# Example of seeking to a certain
position
>>>fp = open('file.txt','r')
>>>fp.seek(10,0)
>>>content = fp.read(10)
>>>print content
ports more
>>>fp.close()
# Example of reading a certain
number of bytes
>>>fp = open('file.txt','r')
>>>fp.read(10)
'Python sup'
>>>fp.close()
# Example of getting the current position of
read
>>>fp = open('file.txt','r')
>>>fp.read(10)
'Python sup'
>>>currentpos = fp.tell
>>>print currentpos
<built-in method tell of file object at
0x0000000002391390>
>>>fp.close()
# Example of writing to a file
>>>fo = open('file1.txt','w')
>>>content='This is an example of writing to a file
in Python.'
>>>fo.write(content)
>>>fo.close()
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.
# skimage package listing
skimage/ Top level package
__init__.py Treat directory as a package
color/ color color subpackage
__init__.py
colorconv.py
colorlabel.py
rgb_colors.py
draw/ draw draw subpackage
__init__.py
draw.py
setup.py
exposure/ exposure subpackage
__init__.py
_adapthist.py
exposure.py
feature/ feature subpackage
__init__.py
_brief.py
_daisy.py
...
Raspberry Pi
• Raspberry Pi
• is a low-cost mini-computer
• with the physical size that of a credit card
• runs various flavors of Linux
• Allows interfacing sensors / actuators through GP I/O pins
• Processor: Low power ARM A profile, 700 MHz with 512MB SDRAM
• 2x USB Ports
• Ethernet Port ,and, SPI, I2C, UART I/Fs
• HDMI, Composite Video, Audio - O/Ps
• Display Serial Interface (DSI)
• Camera Serial Interface (CSI)
• Status LEDs (SD Card Access. 3.3V power, Full-duplex LAN connected etc)
• SD Card Slot
• Power Input Supports various flavors of Linux: Raspbian (Debian Wheezy port optimized for Rpi),
Arch (for AMD devices), Pidora (Fedora Linux optimized for Rpi), RISC OS (a very fast
and compact OS) etc
Considering I/O monitoring + analysis +
storage feasible this platform can be
used for IoT level 1 Nodes!!
This platform can also
be used as a Centralized
Controller (for multiple
monitoring nodes) (or)
as a Gateway
Raspberry Pi 3
Raspberry Pi
Raspberry Pi – Different Boards
RPi 3 RPi 2 RPi B
Cortex A53, 64bit, 1.2GHz, 4
Cores
Cortex A7, 32 bit, 1 GHz, 4 Cores ARM 1176, 32 bit, 700 MHz, 1
Core
1 GB 1 GB 512 MB
4 USB 4 USB 2 USB
WiFi, BT WiFi WiFi
With the help of suitable code show how an LED can be turned ON/OFF using a Raspberry Pi
platform
import RPi.GPIO as GPIO
import time
pin = 40
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin,GPIO.OUT)
try:
GPIO.output (pin,True)
time.sleep(0.5)
GPIO.output(pin,False)
except KeyboardInterrupt:
GPIO.cleanup()
exit()
Implement a Python program for blinking an LED to a Raspberry Pi platform>make suitable
assumptions
import RPi.GPIO as GPIO
import time
pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin,False)
while True:
try:
GPIO.output(pin,True)
time.sleep(0.5)
GPIO.output(pin,False)
time.sleep(0.5)
except KeyboardInterrupt:
GPIO.cleanup()
exit()
IR Sensor
Active Infrared (IR) Beam
This detector consists of two parts, the transmitter and the receiver. The transmitter emits a beam of infrared (IR) light and
the receiver picks up this beam. When the beam is interrupted, the receiver alerts its alarm control panel by opening a relay.
Most beams used in security applications use multiple IR beams in order to reduce false alarms and to increase the area
covered.
Pros
1. Can cover a long range. Some beams extend to 150 meters.
2. Narrow detection area, so eliminating areas like busy thoroughfares is simple.
Cons
1. Installation is tricky because the beam must align with the receiver.
2. Both the receiver and transmitter need power, increasing the amount of wiring required.
3. Prone to false alarms from leaves or birds etc interrupting the beam.
4. Easy to defeat if you know where they are by ducking underneath the beam.
5. Not pet friendly unless you mount them above the height of pets.
PIR Sensor
Passive Infrared (PIR)
The PIR sensor itself has two slots in it, each slot is made of a special material that is sensitive to IR. The lens used here is not
really doing much and so we see that the two slots can 'see' out past some distance (basically the sensitivity of the sensor).
When the sensor is idle, both slots detect the same amount of IR, the ambient amount radiated from the room or walls or
outdoors. When a warm body like a human or animal passes by, it first intercepts one half of the PIR sensor, which causes
a positive differential change between the two halves. When the warm body leaves the sensing area, the reverse happens,
whereby the sensor generates a negative differential change. These change pulses are what is detected.. Like the beams they
usually have more than one detector, both must trigger simultaneously, to avoid false alarms.
Pros
1. Only one unit to install.
2. No alignment issues, just mount it and you’re done.
3. Wide detection area so very difficult to defeat.
4. Pet friendly.
5. Wireless option available.
LDR Sensor
• As its name implies, the Light Dependent Resistor (LDR) is made from a piece of exposed semiconductor material
such as cadmium sulphide that changes its electrical resistance from several thousand Ohms in the dark to only a
few hundred Ohms when light falls upon it by creating hole-electron pairs in the material.
• The net effect is an improvement in its conductivity with a decrease in resistance for an increase in illumination.
Also, photoresistive cells have a long response time requiring many seconds to respond to a change in the light
intensity.
Implement a Python program for interfacing an LED and a Switch to a Raspberry Pi platform
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# Switch pin
GPIO.setup(22,GPIO.IN)
# LED pin
GPIO.setup(23,GPIO.OUT)
state=False
while True:
try:
if (GPIO.input(22) == True):
print("Pressed")
GPIO.output(23, True)
elif (GPIO.input(22) == False):
GPIO.output(23, False)
print("Released")
#time.sleep(0.01)
except KeyboardInterrupt:
exit()
Write a Python program to alert the user in case of movement and/or stand still of intruder
using RPI
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
IR_PIN=18
LIGHT_PIN=25
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.output(LIGHT_PIN, False)
def readIR(pin):
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, False)
time.sleep(0.1)
GPIO.setup(pin,GPIO.IN)
i = GPIO.input(pin)
if i == False:
print("No Intruders",i)
GPIO.output(LIGHT_PIN, False)
elif i == True:
print("Intruders detected",i)
GPIO.output(LIGHT_PIN, True)
try:
while True:
readIR(IR_PIN)
time.sleep(.5)
except KeyboardInterrupt:
GPIO.cleanup()
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN=18
LIGHT_PIN=25
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.output(LIGHT_PIN, False)
def readPIR(pin):
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, False)
time.sleep(0.1)
GPIO.setup(pin,GPIO.IN)
i = GPIO.input(pin)
if i == False:
print("No Intruders", i)
GPIO.output(LIGHT_PIN, False)
elif i == True:
print("Intruders detected",i)
GPIO.output(LIGHT_PIN, True)
try:
while True:
readPIR(PIR_PIN)
time.sleep(.5)
except KeyboardInterrupt:
GPIO.cleanup()
exit()
Write a Python program to Detect the intruder when there is no surrounding lighting using Raspberry Pi
Implement a Python program for switching light based on LDR reading in Raspberry Pi platform>make suitable
assumptions
import RPi.GPIO as GPIO
import time
LDR_PIN=18
LIGHT_PIN=25
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.output(LIGHT_PIN, False)
def LDR(pin):
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, False)
time.sleep(0.1)
GPIO.setup(pin,GPIO.IN)
i = GPIO.input(pin)
if i == False:
print("ambient light is present",i)
GPIO.output(LIGHT_PIN, False)
elif i == True:
print("ambient light is not present",i)
GPIO.output(LIGHT_PIN, True)
try:
while True:
LDR(LDR_PIN)
time.sleep(.5)
except KeyboardInterrupt:
GPIO.cleanup()
exit()
Email id:
shobha_shankar@msrit.edu

More Related Content

Similar to Programming RPi for IoT Applications.pdf

python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxlemonchoos
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptxMohammedAlYemeni1
 
DATA MINING USING R (1).pptx
DATA MINING USING R (1).pptxDATA MINING USING R (1).pptx
DATA MINING USING R (1).pptxmyworld93
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptJoshCasas1
 
Python by ravi rajput hcon groups
Python by ravi rajput hcon groupsPython by ravi rajput hcon groups
Python by ravi rajput hcon groupsRavi Rajput
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
Language-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchLanguage-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchAndrew Lowe
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on pythonwilliam john
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Filesprimeteacher32
 
Government Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxGovernment Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxShivamDenge
 
TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)Mike Felch
 

Similar to Programming RPi for IoT Applications.pdf (20)

C
CC
C
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
Python ppt
Python pptPython ppt
Python ppt
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
DATA MINING USING R (1).pptx
DATA MINING USING R (1).pptxDATA MINING USING R (1).pptx
DATA MINING USING R (1).pptx
 
Python_intro.ppt
Python_intro.pptPython_intro.ppt
Python_intro.ppt
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Python by ravi rajput hcon groups
Python by ravi rajput hcon groupsPython by ravi rajput hcon groups
Python by ravi rajput hcon groups
 
FINAL.ppt
FINAL.pptFINAL.ppt
FINAL.ppt
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Shivam PPT.pptx
Shivam PPT.pptxShivam PPT.pptx
Shivam PPT.pptx
 
Language-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchLanguage-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible research
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on python
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
intro to python.pptx
intro to python.pptxintro to python.pptx
intro to python.pptx
 
Government Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxGovernment Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptx
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)
 

Recently uploaded

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 

Recently uploaded (20)

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 

Programming RPi for IoT Applications.pdf

  • 1. Programming RPi for IoT Applications Presented by Dr Shobha K R Past Chair IEEE Bangalore Section Sensors Council Chapter Senior IEEE member, LMISTE, MWIE, MISOC,IAENG, Technical head of ISOC Rural development SIG Professor, Dept of TCE Ramaiah Institute of Technology
  • 2. Agenda • Basics of Python • RPI Basics • RPI coding
  • 3. Motivation to use Python • Python language employs intuitive key-words, simpler syntax – so easy to learn • Python code is compact • Python is supported on wider range of platforms – so code is portable • Wide library support • Meets the end-to-end development needs of IoT systems – for capturing sensor data, web services, web applications, analytical components
  • 4. Python • Python is a general-purpose high level programming language and suitable for providing a solid foundation to the reader in the area of cloud computing. • The main characteristics of Python are: • 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.
  • 5. Python - Benefits • Easy-to-learn, read and maintain • Python is a minimalistic language with relatively few keywords, uses English keywords and has fewer syntactical constructions as compared to other languages. Reading Python programs feels like English with pseudo-code like constructs. Python is easy to learn yet an extremely powerful language for a wide range of applications. • Object and Procedure Oriented • Python supports both procedure-oriented programming and object-oriented programming. Procedure oriented paradigm allows programs to be written around procedures or functions that allow reuse of code. Procedure oriented paradigm allows programs to be written around objects that include both data and functionality. • Extendable • Python is an extendable language and allows integration of low-level modules written in languages such as C/C++. This is useful when you want to speed up a critical portion of a program. • Scalable • Due to the minimalistic nature of Python, it provides a manageable structure for large programs. • Portable • Since Python is an interpreted language, programmers do not have to worry about compilation, linking and loading of programs. Python programs can be directly executed from source • Broad Library Support • Python has a broad library support and works on various platforms such as Windows, Linux, Mac, etc.
  • 6. Python - Setup • Windows • 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 #Install 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 libbz2-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
  • 7. Numbers • 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. #Integer >>>a=5 >>>type(a) <type ’int’> #Floating Point >>>b=2.5 >>>type(b) <type ’float’> #Long >>>x=9898878787676L >>>type(x) <type ’long’> #Complex >>>y=2+5j >>>y (2+5j) >>>type(y) <type ’complex’> >>>y.real 2 >>>y.imag 5 #Addition >>>c=a+b >>>c 7.5 >>>type(c) <type ’float’> #Subtraction >>>d=a-b >>>d 2.5 >>>type(d) <type ’float’> #Multiplication >>>e=a*b >>>e 12.5 >>>type(e) <type ’float’> #Division >>>f=b/a >>>f 0.5 >>>type(f) <type float’> #Power >>>g=a**2 >>>g 25
  • 8. Strings • 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. #Create string >>>s="Hello World!" >>>type(s) <type ’str’> #String concatenation >>>t="This is sample program." >>>r = s+t >>>r ’Hello World!This is sample program.’ #Get length of string >>>len(s) 12 #Convert string to integer >>>x="100" >>>type(s) <type ’str’> >>>y=int(x) >>>y 100 #Print string >>>print s Hello World! #Formatting output >>>print "The string (The string (Hello World!) has 12 characters #Convert to upper/lower case >>>s.upper() ’HELLO WORLD!’ >>>s.lower() ’hello world!’ #Accessing sub-strings >>>s[0] ’H’ >>>s[6:] ’World!’ >>>s[6:-1] ’World’ #strip: Returns a copy of the string with the #leading and trailing characters removed. >>>s.strip("!") ’Hello World’
  • 9. Lists • Lists • List 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. #Create List >>>fruits=[’apple’,’orange’,’ba nana’,’mango’] >>>type(fruits) <type ’list’> #Get Length of List >>>len(fruits) 4 #Access List Elements >>>fruits[1] ’orange’ >>>fruits[1:3] [’orange’, ’banana’] >>>fruits[1:] [’orange’, ’banana’, ’mango’] #Appending an item to a list >>>fruits.append(’pear’) >>>fruits [’apple’, ’orange’, ’banana’, ’mango’, ’pear’] #Removing an item from a list >>>fruits.remove(’mango’) >>>fruits [’apple’, ’orange’, ’banana’, ’pear’] #Inserting an item to a list >>>fruits.insert(1,’mango’) >>>fruits [’apple’, ’mango’, ’orange’, ’banana’, ’pear’] #Combining lists >>>vegetables=[’potato’,’carrot’,’ onion’,’beans’,’radish’] >>>vegetables [’potato’, ’carrot’, ’onion’, ’beans’, ’radish’] >>>eatables=fruits+vegetables >>>eatables [’apple’, ’mango’, ’orange’, ’banana’, ’pear’, ’potato’, ’carrot’, ’onion’, ’beans’, ’radish’] #Mixed data types in a list >>>mixed=[’data’,5,100.1,8287398L] >>>type(mixed) <type ’list’> >>>type(mixed[0]) <type ’str’> >>>type(mixed[1]) <type ’int’> >>>type(mixed[2]) <type ’float’> >>>type(mixed[3]) <type ’long’> #Change individual elements of a list >>>mixed[0]=mixed[0]+" items" >>>mixed[1]=mixed[1]+1 >>>mixed[2]=mixed[2]+0.05 >>>mixed [’data items’, 6, 100.14999999999999, 8287398L] #Lists can be nested >>>nested=[fruits,vegetables] >>>nested [[’apple’, ’mango’, ’orange’, ’banana’, ’pear’], [’potato’, ’carrot’, ’onion’, ’beans’, ’radish’]]
  • 10. 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. #Create a Tuple >>>fruits=("apple","mango","banana", "pineapple") >>>fruits (’apple’, ’mango’, ’banana’, ’pineapple’) >>>type(fruits) <type ’tuple’> #Get length of tuple >>>len(fruits) 4 #Get an element from a tuple >>>fruits[0] ’apple’ >>>fruits[:2] (’apple’, ’mango’) #Combining tuples >>>vegetables=(’potato’,’carrot’,’onion’,’radis h’) >>>eatables=fruits+vegetables >>>eatables (’apple’, ’mango’, ’banana’, ’pineapple’, ’potato’, ’carrot’, ’onion’, ’radish’)
  • 11. Dictionaries • 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. #Create a dictionary >>>student={’name’:’Mary’,’id’:’8776’,’major’:’CS’ } >>>student {’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’} >>>type(student) <type ’dict’> #Get length of a dictionary >>>len(student) 3 #Get the value of a key in dictionary >>>student[’name’] ’Mary’ #Get all items in a dictionary >>>student.items() [(’gender’, ’female’), (’major’, ’CS’), (’name’, ’Mary’), (’id’, ’8776’)] #Get all keys in a dictionary >>>student.keys() [’gender’, ’major’, ’name’, ’id’] #Get all values in a dictionary >>>student.values() [’female’, ’CS’, ’Mary’, ’8776’] #Add new key-value pair >>>student[’gender’]=’female’ >>>student {’gender’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’} #A value in a dictionary can be another dictionary >>>student1={’name’:’David’,’id’:’9876’,’major’:’ECE’} >>>students={’1’: student,’2’:student1} >>>students {’1’: {’gender’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}, ’2’: {’ major’: ’ECE’, ’name’: ’David’, ’id’: ’9876’}} #Check if dictionary has a key >>>student.has_key(’name’) True >>>student.has_key(’grade’) False
  • 12. Type Conversions #Convert to string >>>a=10000 >>>str(a) ’10000’ #Convert to int >>>b="2013" >>>int(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’]) • Type conversion examples
  • 13. Control Flow – if statement • The if statement in Python is similar to the if statement in other languages. >>>a = 25**5 >>>if a>10000: print "More" else: print "Less" More >>>s="Hello World" >>>if "World" in s: s=s+"!" print s Hello World! >>>if a>10000: if a<1000000: print "Between 10k and 100k" else: print "More than 100k" elif a==10000: print "Equal to 10k" else: print "Less than 10k" More than 100k >>>student={’name’:’Mary’,’id’:’8776’} >>>if not student.has_key(’major’): student[’major’]=’CS’ >>>student {’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
  • 14. Control Flow – for statement • 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. #Looping over characters in a string helloString = "Hello World" for c in helloString: print c #Looping over keys in a dictionary student = ’name’: ’Mary’, ’id’: ’8776’,’gender’: ’female’, ’major’: ’CS’ for key in student: print "%s: %s" % (key,student[key] #Looping over items in a list fruits=[’apple’,’orange’,’banana’,’mango’] i=0 for item in fruits: print "Fruit-%d: %s" % (i,item) i=i+1
  • 15. Control Flow – while statement • The while statement in Python executes the statements within the while loop as long as the while condition is true. #Prints even numbers upto 100 >>> i = 0 >>> while i<=100: if i%2 == 0: print i i = i+1
  • 16. Control Flow – Range statement • The range statement in Python generates a list of numbers in arithmetic progression. #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] #Generate a list of numbers from 0 – 9 >>>range (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 17. Write the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes numlist = list() while ( True ) : inp = input('Enter a number: ') if inp == 'done' : break value = float(inp) numlist.append(value) print(numlist) print(max(numlist)) print(min(numlist))
  • 18. Functions • 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. 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)) Syntax def functionname( parameters ): “’function_docstring“’ function_suite return [expression]
  • 19. Functions - Default Arguments • 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 def printinfo( name, age = 35 ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return # Now you can call printinfo function printinfo( age = 50, name = "miki" ) printinfo( name = "miki" ) Output Name: miki Age 50 Name: miki Age 35
  • 20. Functions - Passing by Reference • All parameters in the Python functions are passed by reference. • If a parameter is changed within a function the change also reflected back in the calling function. # Function definition is here def changeme( mylist ): "This changes a passed list into this function" print ("Values inside the function before change: ", mylist) mylist[2]=50 print ("Values inside the function after change: ", mylist) return # Now you can call changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist) Output Values inside the function before change: [10, 20, 30] Values inside the function after change: [10, 20, 50] Values outside the function: [10, 20, 50]
  • 21. Functions - Passing by Reference # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4] # This would assi new reference in mylist print ("Values inside the function: ", mylist) return # Now you can call changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist) Output Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
  • 22. Functions - Keyword Arguments • Functions can also be called using keyword arguments that identifies the arguments by the parameter name when the function is called. • This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters def printStudentRecords(name,age=20,major=’CS’): print( "Name: " , name) print ("Age: " , age) print ("Major: “ , major) #This will give error as name is required argument printStudentRecords() Output Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: printStudentRecords() takes at least 1 argument (0 given) #Correct use printStudentRecords(name=’Alex’) Name: Alex Age: 20 Major: CS printStudentRecords(name=’Bob’,age=22,major=’ECE’) Name: Bob Age: 22 Major: ECE printStudentRecords(name=’Alan’,major=’ECE’) Name: Alan Age: 20 Major: ECE
  • 23. Functions - Variable Length Arguments • Python functions can have variable length arguments. The variable length arguments are passed to as a tuple to the function with an argument prefixed with asterix (*) Output is: 10 Output is: 70 60 50 # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print ("Output is: ") print (arg1) for var in vartuple: print (var) return # Now you can call printinfo function printinfo( 10 ) printinfo( 70, 60, 50 )
  • 24. Modules • Python allows organizing 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. #student module - saved as student.py 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: " % (i)) print ("Name: " ,students[key]['name']) print "Grade: " ,str(students[key]['grade']) i = i+1 #Using student module >>>import student >>>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 >>>student.printRecords(students) There are 5 students Student-1: Name: Bob Grade: 2.5 Student-2: Name: David Grade: 4.2 Student-3: Name: Mary Grade: 3.5 Student-4: Name: Alex Grade: 3.8 Student-5: Name: John Grade: 4.1 >>>avg = student. averageGrade(students) >>>print ("The average garde is: %0.2f" % (avg)) 3.62 # Importing a specific function from a module >>>from student import averageGrade # Listing all names defines in a module >>>dir(student)
  • 25. 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. • If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size • After the file contents have been read the close function is called which closes the file object. # Example of reading line by line >>>fp = open('file1.txt','r') >>>print( "Line-1: " , fp.readline()) Line-1: Python supports more than one programming paradigms. >>>print ("Line-2: " , fp.readline()) Line-2: Python is an interpreted language. >>>fp.close() # Example of reading an entire file >>>fp = open('file.txt','r') >>>content = fp.read() >>>print content This is a test file. >>>fp.close() # Example of reading lines in a loop >>>fp = open(’file1.txt’,’r’) >>>lines = fp.readlines() >>>for line in lines: print( line) Python supports more than one programming paradigms. Python is an interpreted language. # Syntax for opening a file file object = open(file_name [, access_mode][, buffering])
  • 26. File Handling # Example of seeking to a certain position >>>fp = open('file.txt','r') >>>fp.seek(10,0) >>>content = fp.read(10) >>>print content ports more >>>fp.close() # Example of reading a certain number of bytes >>>fp = open('file.txt','r') >>>fp.read(10) 'Python sup' >>>fp.close() # Example of getting the current position of read >>>fp = open('file.txt','r') >>>fp.read(10) 'Python sup' >>>currentpos = fp.tell >>>print currentpos <built-in method tell of file object at 0x0000000002391390> >>>fp.close() # Example of writing to a file >>>fo = open('file1.txt','w') >>>content='This is an example of writing to a file in Python.' >>>fo.write(content) >>>fo.close()
  • 27. 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. # skimage package listing skimage/ Top level package __init__.py Treat directory as a package color/ color color subpackage __init__.py colorconv.py colorlabel.py rgb_colors.py draw/ draw draw subpackage __init__.py draw.py setup.py exposure/ exposure subpackage __init__.py _adapthist.py exposure.py feature/ feature subpackage __init__.py _brief.py _daisy.py ...
  • 28. Raspberry Pi • Raspberry Pi • is a low-cost mini-computer • with the physical size that of a credit card • runs various flavors of Linux • Allows interfacing sensors / actuators through GP I/O pins • Processor: Low power ARM A profile, 700 MHz with 512MB SDRAM • 2x USB Ports • Ethernet Port ,and, SPI, I2C, UART I/Fs • HDMI, Composite Video, Audio - O/Ps • Display Serial Interface (DSI) • Camera Serial Interface (CSI) • Status LEDs (SD Card Access. 3.3V power, Full-duplex LAN connected etc) • SD Card Slot • Power Input Supports various flavors of Linux: Raspbian (Debian Wheezy port optimized for Rpi), Arch (for AMD devices), Pidora (Fedora Linux optimized for Rpi), RISC OS (a very fast and compact OS) etc Considering I/O monitoring + analysis + storage feasible this platform can be used for IoT level 1 Nodes!! This platform can also be used as a Centralized Controller (for multiple monitoring nodes) (or) as a Gateway
  • 31. Raspberry Pi – Different Boards RPi 3 RPi 2 RPi B Cortex A53, 64bit, 1.2GHz, 4 Cores Cortex A7, 32 bit, 1 GHz, 4 Cores ARM 1176, 32 bit, 700 MHz, 1 Core 1 GB 1 GB 512 MB 4 USB 4 USB 2 USB WiFi, BT WiFi WiFi
  • 32. With the help of suitable code show how an LED can be turned ON/OFF using a Raspberry Pi platform import RPi.GPIO as GPIO import time pin = 40 GPIO.setmode(GPIO.BOARD) GPIO.setup(pin,GPIO.OUT) try: GPIO.output (pin,True) time.sleep(0.5) GPIO.output(pin,False) except KeyboardInterrupt: GPIO.cleanup() exit()
  • 33. Implement a Python program for blinking an LED to a Raspberry Pi platform>make suitable assumptions import RPi.GPIO as GPIO import time pin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(pin,GPIO.OUT) GPIO.output(pin,False) while True: try: GPIO.output(pin,True) time.sleep(0.5) GPIO.output(pin,False) time.sleep(0.5) except KeyboardInterrupt: GPIO.cleanup() exit()
  • 34. IR Sensor Active Infrared (IR) Beam This detector consists of two parts, the transmitter and the receiver. The transmitter emits a beam of infrared (IR) light and the receiver picks up this beam. When the beam is interrupted, the receiver alerts its alarm control panel by opening a relay. Most beams used in security applications use multiple IR beams in order to reduce false alarms and to increase the area covered. Pros 1. Can cover a long range. Some beams extend to 150 meters. 2. Narrow detection area, so eliminating areas like busy thoroughfares is simple. Cons 1. Installation is tricky because the beam must align with the receiver. 2. Both the receiver and transmitter need power, increasing the amount of wiring required. 3. Prone to false alarms from leaves or birds etc interrupting the beam. 4. Easy to defeat if you know where they are by ducking underneath the beam. 5. Not pet friendly unless you mount them above the height of pets.
  • 35. PIR Sensor Passive Infrared (PIR) The PIR sensor itself has two slots in it, each slot is made of a special material that is sensitive to IR. The lens used here is not really doing much and so we see that the two slots can 'see' out past some distance (basically the sensitivity of the sensor). When the sensor is idle, both slots detect the same amount of IR, the ambient amount radiated from the room or walls or outdoors. When a warm body like a human or animal passes by, it first intercepts one half of the PIR sensor, which causes a positive differential change between the two halves. When the warm body leaves the sensing area, the reverse happens, whereby the sensor generates a negative differential change. These change pulses are what is detected.. Like the beams they usually have more than one detector, both must trigger simultaneously, to avoid false alarms. Pros 1. Only one unit to install. 2. No alignment issues, just mount it and you’re done. 3. Wide detection area so very difficult to defeat. 4. Pet friendly. 5. Wireless option available.
  • 36. LDR Sensor • As its name implies, the Light Dependent Resistor (LDR) is made from a piece of exposed semiconductor material such as cadmium sulphide that changes its electrical resistance from several thousand Ohms in the dark to only a few hundred Ohms when light falls upon it by creating hole-electron pairs in the material. • The net effect is an improvement in its conductivity with a decrease in resistance for an increase in illumination. Also, photoresistive cells have a long response time requiring many seconds to respond to a change in the light intensity.
  • 37. Implement a Python program for interfacing an LED and a Switch to a Raspberry Pi platform import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # Switch pin GPIO.setup(22,GPIO.IN) # LED pin GPIO.setup(23,GPIO.OUT) state=False while True: try: if (GPIO.input(22) == True): print("Pressed") GPIO.output(23, True) elif (GPIO.input(22) == False): GPIO.output(23, False) print("Released") #time.sleep(0.01) except KeyboardInterrupt: exit()
  • 38. Write a Python program to alert the user in case of movement and/or stand still of intruder using RPI import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) IR_PIN=18 LIGHT_PIN=25 GPIO.setup(LIGHT_PIN, GPIO.OUT) GPIO.output(LIGHT_PIN, False) def readIR(pin): GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, False) time.sleep(0.1) GPIO.setup(pin,GPIO.IN) i = GPIO.input(pin) if i == False: print("No Intruders",i) GPIO.output(LIGHT_PIN, False) elif i == True: print("Intruders detected",i) GPIO.output(LIGHT_PIN, True) try: while True: readIR(IR_PIN) time.sleep(.5) except KeyboardInterrupt: GPIO.cleanup()
  • 39. import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) PIR_PIN=18 LIGHT_PIN=25 GPIO.setup(LIGHT_PIN, GPIO.OUT) GPIO.output(LIGHT_PIN, False) def readPIR(pin): GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, False) time.sleep(0.1) GPIO.setup(pin,GPIO.IN) i = GPIO.input(pin) if i == False: print("No Intruders", i) GPIO.output(LIGHT_PIN, False) elif i == True: print("Intruders detected",i) GPIO.output(LIGHT_PIN, True) try: while True: readPIR(PIR_PIN) time.sleep(.5) except KeyboardInterrupt: GPIO.cleanup() exit() Write a Python program to Detect the intruder when there is no surrounding lighting using Raspberry Pi
  • 40. Implement a Python program for switching light based on LDR reading in Raspberry Pi platform>make suitable assumptions import RPi.GPIO as GPIO import time LDR_PIN=18 LIGHT_PIN=25 GPIO.setup(LIGHT_PIN, GPIO.OUT) GPIO.output(LIGHT_PIN, False) def LDR(pin): GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, False) time.sleep(0.1) GPIO.setup(pin,GPIO.IN) i = GPIO.input(pin) if i == False: print("ambient light is present",i) GPIO.output(LIGHT_PIN, False) elif i == True: print("ambient light is not present",i) GPIO.output(LIGHT_PIN, True) try: while True: LDR(LDR_PIN) time.sleep(.5) except KeyboardInterrupt: GPIO.cleanup() exit()