UNIT-3
Introduction to Python Programming
Introduction to Internet of Things 1
Why Python?
Python is a versatile language which is easy to script and easy to
read.
It doesn’t support strict rules for syntax.
Its installation comes with integrated development environment
for programming.
It supports interfacing with wide ranging hardware platforms.
With open-source nature, it forms a strong backbone to build large
applications.
Introduction to Internet of Things 2
Python IDE
Python IDE is a free and open source software that is used to
write codes, integrate several modules and libraries.
It is available for installation into PC with Windows, Linux and
Mac.
Examples: Spyder, PyCharm, etc.
Introduction to Internet of Things 3
Starting with
Python
Simple printing statement at the python interpreter prompt,
>>> print “Hi, Welcome to python!”
Output: Hi, Welcome to python!
To indicate different blocks of code, it follows rigid indentation.
if True:
print “Correct"
else:
print “Error"
Introduction to Internet of Things 4
Data- types in
Python
There are 5 data types in Python:
Numbers
x, y, z = 10, 10.2, " Python "
String
x = ‘This is Python’
print x >>This is Python
print x[0] >>T
print x[2:4] >>is
Introduction to Internet of Things 5
Data- types in Python
(contd..)
List
x = [10, 10.2, 'python']
Tuple
Dictionary
d = {1:‘item','k':2}
Introduction to Internet of Things 6
Controlling
Statements
if (cond.): while (cond.):
statement 1 statement 1
statement 2 statement 2
x = [1,2,3,4]
elif (cond.):
for i in x:
statement 1
statement 1
statement 2 statement 2
else:
statement 1
statement 2
Introduction to Internet of Things 7
Controlling Statements
(contd..)
Break Continue
for s in "string": for s in "string":
if s == ‘n': if s == ‘y':
break continue
print (s) print (s)
print print “End”
“End”
Introduction to Internet of Things 8
Functions in Python
Defining a function
Without return value
def funct_name(arg1, arg2, arg3): # Defining the function
statement 1
statement 2
With return value
def funct_name(arg1, arg2, arg3): # Defining the function
statement 1
statement 2
return x # Returning the value
Introduction to Internet of Things 9
Functions in Python
Calling a function
def example (str):
print (str + “!”)
example (“Hi”) # Calling the function
Output:: Hi!
Introduction to Internet of Things 10
Functions in Python
(contd..)
Example showing function returning multiple values
def greater(x, y):
if x > y:
return x, y
else:
return
y, x
val = greater(10,
100) print(val)
Output:: (100,10)
Introduction to Internet of Things 11
Functions as Objects
Functions can also be assigned and reassigned to the variables.
Example:
def add (a,b)
return a+b
print (add(4,6))
c = add(4,6)
print c
Output:: 10 10
Introduction to Internet of Things 12
Variable Scope in Python
Global variables:
These are the variables declared out of any function , but can be
accessed inside as well as outside the function.
Local variables:
These are the ones that are declared inside a function.
Introduction to Internet of Things 13
Example showing Global Variable
g_var = 10
def example():
l_var = 100
print(g_var)
example() # calling the function
Output:: 10
Introduction to Internet of Things 14
Example showing Variable Scope
var = 10
def example():
var = 100
print(var)
example() # calling the function
print(var)
Output:: 100
10
Introduction to Internet of Things 15
Modules in Python
Any segment of code fulfilling a particular task that can be
used commonly by everyone is termed as a module.
Syntax:
import module_name #At the top of the code
using module_name.var #To access functions and values
with ‘var’ in the module
Introduction to Internet of Things 16
Modules in Python
(contd..)
Example:
import random
for i in range(1,10):
val = [Link](1,10)
print (val)
Output:: varies with each execution
Introduction to Internet of Things 17
Modules in Python
(contd..)
We can also access only a particular function from a module.
Example:
from math import pi
print (pi)
Output:: 3.14159
Introduction to Internet of Things 18
Exception Handling in
Python
An error that is generated during execution of a program, is
termed as exception.
Syntax:
try:
statements
except _Exception_:
statement
s else:
statemen
ts
Introduction to Internet of Things 19
Exception Handling in Python
(contd..)
Example:
while True:
try:
n = input ("Please enter an integer: ")
n = int (n)
break
except ValueError:
print
"No valid
integer! "
print “It is an
integer!"
Introduction to Internet of Things 20
Example Code: to check number is prime or
not
x = int (input("Enter a number: "))
def prime (num):
if num > 1:
for i in
range(2,num):
if (num % i)
== 0:
print (num,"is not a prime number")
print (i,“is a factor of”,num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
prime (x)
Introduction to Internet of Things 21
File Read Write
Operations
Python allows you to read and write files
No separate module or library required
Three basic steps
Open a file
Read/Write
Close the file
Introduction to Internet of Things 2
File Read Write Operations
(contd..)
Opening a File:
Open() function is used to open a file, returns a file object
open(file_name, mode)
Mode: Four basic modes to open a file
r: read mode
w: write mode
a: append mode
r+: both read
and write mode
Introduction to Internet of Things 3
File Read Write Operations
(contd..)
Read from a file:
read(): Reads from a file
file=open(‘[Link]’, ‘r’)
[Link]()
Write to a file:
Write(): Writes to a file
file=open(‘[Link]’, ‘w’)
[Link](‘writing to the file’)
Introduction to Internet of Things 4
File Read Write Operations
(contd..)
Closing a file:
Close(): This is done to ensure that the file is free to use for other resources
[Link]()
Using WITH to open a file:
Good practice to handle exception while file read/write operation
Ensures the file is closed after the operation is completed, even if an exception is
encountered
Introduction to Internet of Things 5
File Read Write Operations code +
image
with open("[Link]","w") as file:
[Link]("Writing data")
[Link]()
with open("[Link]","r") as file:
f=[Link]()
print('Reading from the file\n')
print (f)
[Link]()
Introduction to Internet of Things 6
File Read Write Operations
(contd..)
Comma Separated Values Files
CSV module supported for CSV files
Read: Write:
with open(file, "r") as csv_file: data = ["1,2,3,4,5,6,7,8,9".split(",")]
reader = [Link](csv_file) file = "[Link]"
print("Reading from the CSV File\n") with open(file, "w") as csv_file:
for row in reader: writer = [Link](csv_file, delimiter=',')
print(" ".join(row)) print("Writing CSV")
csv_file.close() for line in data:
[Link](line)
csv_file.close()
Introduction to Internet of Things 7
File Read Write Operations
(contd..)
Introduction to Internet of Things 8
Image Read/Write
Operations
Python supports PIL library for image related operations
Install PIL through PIP
sudo pip install pillow
PIL is supported till python version 2.7. Pillow supports the 3x version of
python.
Introduction to Internet of Things 9
Image Read/Write
Operations
Reading Image in Python:
PIL: Python Image Library is used to work with image files
from PIL import Image
Open an image file
image=[Link](image_name)
Display the image
[Link]()
Introduction to Internet of Things 10
Image Read/Write Operations
(contd..)
Resize(): Resizes the image to the specified size
[Link](255,255)
Rotate(): Rotates the image to the specified degrees, counter clockwise
[Link](90)
Format: Gives the format of the image
Size: Gives a tuple with 2 values as width and height of the image, in pixels
Mode: Gives the band of the image, ‘L’ for grey scale, ‘RGB’ for true colour image
print([Link], [Link], [Link])
Introduction to Internet of Things 11
Image Read/Write Operations
(contd..)
Convert image to different mode:
Any image can be converted from one mode to ‘L’ or ‘RGB’
mode
conv_image=[Link](‘L’)
Conversion between modes other that ‘L’ and ‘RGB’ needs
conversion into any of these 2 intermediate mode
Introduction to Internet of Things 12
Output
Converting a sample image to Grey Scale
Introduction to Internet of Things 13
Outpu
t
Introduction to Internet of Things 14
Networking in
Python
Python provides network services for client server model.
Socket support in the operating system allows to implement clients
and servers for both connection-oriented and connectionless
protocols.
Python has libraries that provide higher-level access to specific
application-level network protocols.
Introduction to Internet of Things 15
Networking in Python
(contd..)
Syntax for creating a socket:
s = [Link] (socket_family, socket_type, protocol=0)
socket_family − AF_UNIX or AF_INET
socket_type − SOCK_STREAM or SOCK_DGRAM
protocol − default ‘0’.
Introduction to Internet of Things 16
Example - simple
server
The socket waits until a client connects to the port, and then returns a
connection object that represents the connection to that client.
import socket
import sys
# Create a
TCP/IP socket
sock =
[Link](
socket.AF_IN
ET,
socket.SOCK_
STREAM)
Introduction to Internet of Things 17
# Bind the socket to the port
Example - simple server
(contd..)
# Listen for incoming connections
[Link](1)
connection, client_address = [Link]()
#Receive command
data = [Link](1024)
print(data)
[Link]()
Introduction to Internet of Things 18
Example - simple
client
import socket
import sys
# Create a
TCP/IP socket
client_socket
=
[Link](
socket.AF_IN
ET,
socket.SOCK_
STREAM)
#Connect to Listener socket
Introduction to Internet of Things 19
client_socket.connect(("[Link]", 2017))
Code Snapshot
Introduction to Internet of Things 20
Outpu
t
Introduction to Internet of Things 21
Introduction to Raspberry Pi
1
Introduction to Internet of
What is Raspberry
Pi?
• Computer in your palm.
• Single-board computer.
• Low cost.
• Easy to access.
2
Introduction to Internet of
Variants and Specifications of
Raspberry Pi
Key features Raspberry pi 3 model B Raspberry pi 2 Raspberry Pi zero
model B
RAM 1GB SDRAM 1GB SDRAM 512 MB SDRAM
CPU Quad cortex [email protected] Quad cortex ARM 11@ 1GHz
A53@900MHz
GPU 400 MHz video core IV 250 MHz video core IV 250 MHz video core IV
Ethernet 10/100 10/100 None
Wireless 802.11/Bluetooth 4.0 None None
Video output HDMI/Composite HDMI/Composite HDMI/Composite
GPIO 40 40 40
3
Introduction to Internet of
Basic Architecture
RAM
I/O CPU/GPU USB HUB
ETHERNET USB
4
Introduction to Internet of
Raspberry Pi
Introduction to Internet of Things 5
Start up raspberry
pi
Introduction to Internet of
Raspberry Pi GPIO
• Act as both digital output and digital input.
• Output: turn a GPIO pin high or low.
• Input: detect a GPIO pin high or low.
Introduction to Internet of Things 7
Raspberry Pi pin configuration
Source: Raspberry Pi PCB Pin Overview, Wikimedia Commons (Online) Source: Raspberry Pi GPIO, Wikimedia Commons (Online)
Basic Set up for Raspberry
Pi
• HDMI cable.
• Monitor.
• Key board.
• Mouse.
• 5volt power adapter for raspberry pi.
• LAN cable .
• Min- 2GB micro sd card
Basic Set up for Raspberry
Pi
Operating
System
Official Supported OS :
• Raspbian
• NOOBS
Some of the third party OS :
• UBUNTU mate
• Snappy Ubuntu core
• Windows 10 core
• Pinet
• Risc OS
Source: Downloads, Raspberry Pi Foundation
Raspberry Pi
Setup
Download Raspbian:
• Download latest Raspbian image from raspberry pi official site:
[Link]
• Unzip the file and end up with an .img file.
Raspberry Pi OS Setup
Write Raspbian in SD card :
• Install “Win32 Disk Imager” software in windows machine .
• Run Win32 Disk Imager
• Plug SD card into your PC
• Select the “Device”
• Browse the “Image File”(Raspbian image)
• Write
Raspberry Pi OS Setup
Basic Initial Configuration
Enable SSH
Step1 : Open command prompt and type sudo raspi-config and press enter.
Step2: Navigate to SSH in the Advance option.
Step3: Enable SSH
Basic Initial Configuration
Basic Initial Configuration
contd.
Expand file system :
Step 1: Open command prompt and type sudo raspi-config and press enter.
Step 2: Navigate to Expand Filesystem
Step 3: Press enter to expand it.
Basic Initial Configuration
contd.
Programming
Default installed :
• Python
•C
• C++
• Java
• Scratch
• Ruby
Note : Any language that will compile for ARMv6 can be used with raspberry pi.
Source: Programming languages for Raspberry Pi, eProseed, Lonneke Dikmans, August 07, 2015
Popular Applications
• Media streamer
• Home automation
• Controlling BOT
• VPN
• Light weight web server for IOT
• Tablet computer
Topics Covered
Using GPIO pins
Taking pictures using PiCam
Introduction to Internet of Things 2
Blinking LED
Requirement:
Raspberry pi
LED
100 ohm resistor
Bread board
Jumper cables
Introduction to Internet of Things 3
Blinking LED
(contd..)
Installing GPIO library:
Open terminal
Enter the command “sudo apt-get install python-dev” to install python
development
Enter the command “sudo apt-get install [Link]” to install
GPIO library.
Introduction to Internet of Things 4
Blinking LED
(contd..)
Connection:
Connect the negative terminal of
the LED to the ground pin of Pi
Connect the positive terminal of
the LED to the output pin of Pi
Introduction to Internet of Things 5
Blinking LED
(contd..)
Basic python coding:
Open terminal enter the command
sudo nano [Link]
This will open the nano editor where you can write your code
Ctrl+O : Writes the code to the file
Ctrl+X : Exits the editor
Introduction to Internet of Things 6
Blinking LED
(contd..)
Code: #GPIO library
import [Link] as GPIO
import time # Set the type of board for pin numbering
[Link]([Link])# Set GPIO pin 11as output pin
[Link](11, [Link])
# Turn on GPIO pin 11
for i in range (0,5):
[Link](11,True)
[Link](1)
[Link](11,False)
[Link](2)
[Link](11,True)
[Link]()
Introduction to Internet of Things 7
Blinking LED
(contd..)
Introduction to Internet of Things 8
Blinking LED
(contd..)
The LED blinks in a loop with delay
of 1 and 2 seconds.
Introduction to Internet of Things 9
Capture Image using Raspberry
Pi
Introduction to Internet of Things 10
Requiremen
t
Raspberry Pi
Raspberry Pi Camera
Introduction to Internet of Things 11
Raspberry Pi
Camera
Raspberry Pi specific camera
module
Dedicated CSI slot in Pi for
connection
The cable slot is placed
between Ethernet port and
HDMI port
Introduction to Internet of Things 12
Connection
Boot the Pi once the camera is connected to Pi
Introduction to Internet of Things 13
Configuring Pi for
Camera
In the terminal run the command “sudo raspi-config” and press
enter.
Navigate to “Interfacing Options” option and press enter.
Navigate to “Camera” option.
Enable the camera.
Reboot Raspberry pi.
Introduction to Internet of Things 14
Configuring Pi for Camera
(contd..)
Introduction to Internet of Things 15
Capture
Image
Open terminal and enter the command-
raspistill -o [Link]
This will store the image as ‘[Link]’
Introduction to Internet of Things 16
Capture Image
(contd..)
PiCam can also be processed using Python camera module python-picamera
sudo apt-get install python-picamera
Python Code:
Import picamera
camera = [Link]()
[Link]('[Link]')
Source: PYTHON PICAMERA, Raspberry Pi Foundation
Introduction to Internet of Things 17
Capture Image
(contd..)
Introduction to Internet of Things 18
Implementation of IoT with Raspberry Pi
Introduction to Internet of Things 1
IO
T
Internet Of Things
Creating an interactive environment
Network of devices connected
together
Introduction to Internet of Things 2
Senso
r
Electronic element
Converts physical quantity into electrical signals
Can be analog or digital
Introduction to Internet of Things 3
Actuator
Mechanical/Electro-mechanical device
Converts energy into motion
Mainly used to provide controlled motion to other
components
Introduction to Internet of Things 4
System
Overview
Sensor and actuator interfaced with Raspberry Pi
Read data from the sensor
Control the actuator according to the reading from the
sensor
Connect the actuator to a device
Introduction to Internet of Things 5
System Overview
(contd..)
Requirements
DHT Sensor
4.7K ohm resistor
Relay
Jumper wires
Raspberry Pi
Mini fan
Introduction to Internet of Things 6
DHT Sensor
Digital Humidity and
Temperature Sensor (DHT)
PIN 1, 2, 3, 4 (from left to
right)
PIN 1- 3.3V-5V Power
supply
PIN 2- Data
PIN 3- Null
PIN 4- Ground
Introduction to Internet of Things 7
Relay
Mechanical/electromechanical
switch
3 output terminals (left to
right)
NO (normal open):
Common
NC (normal close)
Introduction to Internet of Things 8
Temperature Dependent Auto Cooling
System
Sensor interface with Raspberry Pi
Connect pin 1 of DHT sensor to the
3.3V pin of Raspberry Pi
Connect pin 2 of DHT sensor to any
input pins of Raspberry Pi, here we
have used pin 11
Connect pin 4 of DHT sensor to the
ground pin of the Raspberry Pi
Introduction to Internet of Things 9
Temperature Dependent Auto Cooling
System (contd..)
Relay interface with Raspberry Pi
Connect the VCC pin of relay to the 5V
supply pin of Raspberry Pi
Connect the GND (ground) pin of relay
to the ground pin of Raspberry Pi
Connect the input/signal pin of Relay to
the assigned output pin of Raspberry Pi
(Here we have used pin 7)
Introduction to Internet of Things 10
Temperature Dependent Auto Cooling
System (contd..)
Adafruit provides a library to work with the DHT22 sensor
Install the library in your Pi-
Get the clone from GIT
git clone
[Link]
adafruit/Adafruit_Py
thon_DHT.g...
Go to folder
Adafruit_Python_DHT
Source: ADAFRUIT DHTXX SENSORS, Lady Ada, 2012-07-29
cd
Adafruit_Python_D
Introduction to Internet of Things 11
HT
Program: DHT22 with
Pi
import [Link] as GPIO
from time import sleep
import Adafruit_DHT #importing the Adafruit library
[Link]([Link])
[Link](False)
sensor = Adafruit_DHT.AM2302 # create an instance of the sensor type
print (‘Getting data from the sensor’)
#humidity and temperature are 2 variables that store the values received from the sensor
humidity, temperature = Adafruit_DHT.read_retry(sensor,17)
print ('Temp={0:0.1f}*C humidity={1:0.1f}%'.format(temperature, humidity))
Introduction to Internet of Things 12
Program: DHT22 interfaced with Raspberry
Pi
Code Output
Introduction to Internet of Things 13
Connection: Relay
Connect the relay pins with the Raspberry Pi as mentioned in previous slides
Set the GPIO pin connected with the relay’s input pin as output in the sketch
[Link](13,[Link])
Set the relay pin high when the temperature is greater than 30
if temperature > 30:
[Link](13,0) # Relay is active low
print(‘Relay is on')
sleep(5)
[Link](13,1) # Relay is turned off
after delay of 5 seconds
Introduction to Internet of Things 14
Connection: Relay
(contd..)
Introduction to Internet of Things 15
Connection: Fan
Connect the Li-po battery in series with the fan
NO terminal of the relay -> positive
terminal of the Fan.
Common terminal of the relay -> Positive terminal of
the battery
Negative terminal of the battery -> Negative terminal
of the fan.
Run the existing code. The fan should operate when the
surrounding temperature is greater than the threshold value
in the sketch
Introduction to Internet of Things 16
Connection: Fan (contd..)
Introduction to Internet of Things 17
Result
The fan is switched on whenever
the temperature is above the
threshold value set in the code.
Notice the relay indicator turned
on.
18