Unit 3
Unit 3
Source : ITU-T
IoT – Basic Idea
Interfacing sensors to the computing unit
Breadboard
Raspberry Pi Jumper wires
Electrical
components
Sensors
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Components
2. Sensors
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Components
3. Actuators
Linear Actuators
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Components
4. Other components
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Interfacing Rpi to components : GPIO ports
Programming the Raspberry Pi :
Learning Python on the Go.......
Module import
GPIO pin setup
Execute in loop
The latest version of Raspbian includes the RPI.GPIO Python library pre-installed,
so you can simply import that into your Python code. The RPI.GPIO is a library that allows your Python application to easily
access the GPIO pins on your Raspberry Pi. The as keyword in Python allows you to refer to the RPI.GPIO library using the
shorter name of GPIO. There are two ways to refer to the pins on the GPIO: either by physical pin numbers (starting from pin 1 to
40 on the Raspberry Pi 2/3), or Broadcom GPIO numbers (BCM)
Introducing Python
1. General-purpose, versatile, and powerful programming languaage
2. It was created by Guido van Rossum in 1991 and was named after the
British comedy show, Monty Python’s Flying Circus.
3. Applications – scripting, web development, data visualization,
data analysis, machine learning
4. Characteristics :
i.Multi-paradigm programming language - Python supports more than one
programming paradigms including object-oriented programming and structured
Programming
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Introducing Python
4. Characteristics :
ii. Interpreted and Interactive language – does not require compilation steps,
Users provide command at the prompt which get executed directly
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
All about Python : Installation, Guide, Docs....
www.python.org
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Using the Python Environment
Invoking the Python environment : Type python at the prompt
Example : and, exec, not, print , continue, def, if , return , import, try, while, else, except, for
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Python Program Structure
Indentation : there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of
code are denoted by line indentation, which is rigidly enforced.
Comments : A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
physical line end are part of the comment, and the Python interpreter ignores them.
Variables : Reserved memory locations that store values, depending on the data type, interpreter allocates memory
and decides what to store in that location. Thus, by assigning different data types to variables, one can store integers,
floating point numbers, strings etc.
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Data Types in Python
There are five standard data types in Python : numbers, string, list, tuple and dictionary
# Floating Point
# Complex Number
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Compound Data Types Python in Linux
Lists : used to group together values
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Compound Data Types Python in Linux
Dictionaries : Hash table that maps keys to values
Operations done on a list :
i. Get the value of a key ii. Get all items iii. Get all keys iv. Add a key value pair v. Check
if dictionary has a key
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Control Flow in Python
# If Statement
>>
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Control Flow in Python
# For-Loop
1. Looping over a string
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Control Flow in Python
# While-Loop # Range #Break ( breaks out of loop)
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Functions in Python
Block of code that takes information (in the form of parameters), does
some computation, and returns a new piece of information based on the
parameter information.
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Handling Files in Python
Files : Python treats files as sequence of lines; Sequence operations work
for the data read from files
Basic operations are : open, close, read and write
open ( filename, mode) – returns a file object
mode can be read(r), write(w), append(a); Mode is optional and Default is r
Example :
>> rivers = open(‘ world_rivers’ ,’ r’ ) // reading from open file returns its content obtained a file object
>> rivers = open(‘ world_rivers’ ,’ w’) // writing in an open file means overwriting the existing contents
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Handling Files in Python
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Handling Files in Python
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Reading Sequential Files in Python
# This program makes a copy of one sequential file into another. It asks the user for the names of the files to read from and to write to:
# A file must be opened --- this requires a new variable to hold the address in heap storage of the file's data-structure representation
>> input = open(inputfilename, "r") # "r" means we will read from input filename
>> output = open(outputfilename, "w") # "w" means we will write to output filename
# You can read the lines one by one with a while loop :
>> line = input.readline() # read the next line of input --- this includes the ending \r and \n characters!
# The line is of course a string.
>> while line != " " : # When the input is all used up, line == ""
print line
output.write(line) # Write the string to the output file
line = input.readline()
# But here is the simplest way to read all the lines one by one :
>> for line in input :
print line
output.write(line)
>> input.close()
>> output.close()
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Exceptions in Python
Python reports to user about some unexpected event through exceptions
These events can be one of the following :
Access violation ( writing to a read only file )
Missing resources ( reading a non-existent file)
Type incompatibility ( multiplying two strings)
Bound violation ( accessing a string beyond limit)
Example :
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Exception Handling in Python
try.......except......else
try: #Program to depict else clause with try-except
Operations that can raise exceptions.
except [Optional list of exceptions] : #Function which returns a/b
In case of exceptions, do the recovery.
def example(a , b):
try:
else : # else is optional
c =((a+b) // (a-b))
If no exception then do normal things except ZeroDivisionError:
print ("a/b result in 0")
else:
try.......finally print (c)
try :
Operations that can raise exceptions. #Driver program to test above function
finally : example(2.0, 3.0) -5.0
example(3.0, 3.0) a/b result in 0
Execute irrespective of whether exception
was raised or not. Typically clean-up stuff
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Modules in Python
Organizing programs for easier maintenance and access
Reuse same functions across programs without copying its definition in each
program
Python allows putting definition in a file – use them in a script or in an interactive
instance
Such a file is called module - definitions from modules can be imported in other
modules or main module
The file name is the module name with .py appended
Within a module, the module’s name is available as global variable name_
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Module Example
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Module Example
Importing special functions
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
_main_ in Modules
When you run a module on the command line with : python fib.py <arguments>
the code in the module will be executed in the module just as if you imported it but with the
name set to " main ".
By adding the code at the end of your module, you can make the file usable as script as well as
importable module
if name == " main ":
Example:
if name == " main ":
import sys
print (fib_iter(int(sys.argv[ 1] )))
• This code parses the command line only if the module is executed as the “ main” file :
$ python fib.py 10
55
• If the module is imported, the code is not run : >>> import fib
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Back to Raspberry Pi Using Python
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Connecting Rpi to Piezo Buzzer
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Rpi used to control intensity of a LED
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Using Rpi to control a Servo Motor
90 degrees 7.5
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Using Rpi to control a Vibration Sensor
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Connecting Rpi to Infrared Sensor
import RPi.GPIO as GPIO
import time
Sensor =16
buzzer =18
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor,GPIO.IN)
GPIO.setup(buzzer,GPIO.OUT)
GPIO.output(buzzer,False)
print "IR Sensor Ready....."
Print " "
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Connecting Rpi to Infrared Sensor
try:
while True:
if GPIO.input(sensor):
GPIO.output(buzzer,True)
print "Object Detected"
while GPIO.input(sensor):
time.sleep(0.2)
else:
GPIO.output(buzzer,False)
except KeyboardInterrupt:
GPIO.cleanup()
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Temperature and Humidity Sensors - DHT11
Temperature and Humidity Sensors are frequently used in soil monitors,
home environment, weather stations. They are simple to program.
DHT11 is a sensor circuit that contains surface mounted thermistor and
humidity sensor. The circuit converts the resistance measurements from the
thermistor and the humidity sensor to digital outputs
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Interfacing Rpi to DHT11
Using the Adafruit DHT 11 library
1. git clone https://github.com/adafruit/Adafruit_Python_DHT.git
2. cd Adafruit_Python_DHT