0% found this document useful (0 votes)
30 views

Unit 3

The document discusses interfacing sensors to Raspberry Pi using Python. It describes the components used including Raspberry Pi, sensors, breadboard and jumper wires. It also provides an overview of Python including its usage for IoT applications and examples of programming concepts like data types, control flow, functions and file handling.

Uploaded by

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

Unit 3

The document discusses interfacing sensors to Raspberry Pi using Python. It describes the components used including Raspberry Pi, sensors, breadboard and jumper wires. It also provides an overview of Python including its usage for IoT applications and examples of programming concepts like data types, control flow, functions and file handling.

Uploaded by

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

Tutorial 2 : Interfacing Sensors to Rpi |

Learning Python on the Go....


The Four Layered IoT Architecture

Source : ITU-T
IoT – Basic Idea
Interfacing sensors to the computing unit
Breadboard
Raspberry Pi Jumper wires

Electrical
components

Sensors

Source: Book website: http://www.internet-of-things-book.com


Components
1. Computing Unit – Raspberry Pi ( 3B/ 3B+ / 4)

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Components
2. Sensors

Ultrasonic Distance Sensor


IR Sensor

Temperature Sensor Tilt Sensor


Vibration Sensor

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Components
3. Actuators

Servo motor Buzzer

Linear Actuators

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Components
4. Other components

Breadboard Internal connections


of a Breadboard

Jumper Wires Resistors LED

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

Send a HIGH signal to pin 18


Wait for 1 time unit
Send a LOW signal to pin 18
Wait for 1 time unit

Python program which instructs the Rpi to blink


a LED - turn the LED high and low alternately

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

iii. Easy to learn and maintain – fewer syntactical constructions,


Statements feel like English with pseudo code constructs

iv. Extendable, Scalable and Portable

v. Broad Range of Library support

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

First Python Program : Interpreted and Interactive

Python Program Structure and Rules


Identifier : name used to identify a variable, function, class, module, or other object. An identifier starts with a
letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9)

Reserved words : words that cannot be used as identifiers

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

- Number : store numeric values, immutable data types

- Strings are list of characters


# Integer # String operation # Type Conversion # Integer Operation

# 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

Operations done on a list


i. Accessing elements ii. insert/remove/append items to list iii. change items in list

Tuple : Read only list

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

2. Looping over a list or dictionary

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Control Flow in Python
# While-Loop # Range #Break ( breaks out of loop)

#Continue ( continues with next operation ) #Pass ( null operation )

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.

- Python, functions begin with the def keyword.

- Parameters in Python function are passed by reference

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

close(filename, mode) – closes the file object, finishes any buffered


operation
Example :
>> rivers = world_rivers.close() // closes the file once done with writing

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 :

>> x = open (‘ world_rivers’ ,’ r’ )


>> x.close
>> x.read() Exception; Bad read, file already closed

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_

File name : fib.py


Module name : fib

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Module Example

Within a module, the


module’s name is
available as the value of
the global variable
name .

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Module Example
Importing special functions

Exports all names except those beginning with underscore

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

Python program which instructs the


Rpi to control a piezoelectric buzzer

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Rpi used to control intensity of a LED

Python program which instructs the


Rpi to fade a LED

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Using Rpi to control a Servo Motor

Position Duty Cycle


0 degree 2.5

90 degrees 7.5

180 degrees 12.5


Python program which controls a
Servo motor

Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal
Using Rpi to control a Vibration Sensor

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

3. sudo apt-get install build-essential python-dev

4. sudo python setup.py install

Python program that instructs the


Rpi to read data from the DHT11
module and print it
Internet of Things
Spring 2022
Instructor : Dr. Bibhas Ghoshal

You might also like