CSE Iot Unit 3
CSE Iot Unit 3
Programming
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.
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.
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"
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
5
Data-types in Python (contd..)
✔ List
x = [10, 10.2, 'python']
✔ Tuple
✔ Dictionary
d = {1:‘item','k':2}
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
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 “End” print “End”
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
# Defining the function
def funct_name(arg1, arg2, arg3):
statement 1
statement 2
return x # Returning the value
9
Functions in Python
▪ Calling a function
def example (str):
print (str + “!”)
Output:: Hi!
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
Output:: (100,10)
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
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.
13
Example showing Global Variable
g_var = 10
def
example():
l_var = 100
print(g_var)
example() # calling the function
Output:: 10
14
Example showing Variable Scope
var = 10
def
example():
var = 100
print(var)
example() # calling the function
print(var)
Output:: 100
10
15
Modules in Python
▪ Any segment of codefulfilling 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
16
Modules in Python (contd..)
▪ Example:
import random
for i in range(1,10):
val =
random.randint(1,10)
print (val)
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
18
Exception Handling in Python
▪ An error that is generated during execution of a program, is
termed as exception.
▪ Syntax:
try:
statements
except
_Exception_:
statements
else:
statements
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!"
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)
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
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
3
File Read Write Operations (contd..)
Read from a file:
▪ read(): Reads from a file
file=open(‘data.txt’, ‘r’)
file.read()
Write to a file:
▪ Write(): Writes to a file
file=open(‘data.txt’, ‘w’)
file.write(‘writing to the file’)
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
file.close()
5
File Read Write Operations code + image
with open("PythonProgram.txt","w") as file:
file.write("Writing data")
file.close()
6
File Read Write Operations (contd..)
Comma Separated Values Files
▪ CSV module supported for CSV files
Read: Write:
7
File Read Write Operations (contd..)
8
Image Read/Write Operations
▪ Python supports PIL library for image related operations
▪ Install PIL through PIP
PIL is supported till python version 2.7. Pillow supports the 3x version of
python.
9
Image Read/Write Operations
Reading Image in Python:
▪ PIL: Python Image Library is used to work with image files
10
Image Read/Write Operations (contd..)
Resize(): Resizes the image to the specified size
image.resize(255,255)
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=image.convert(‘L’)
▪ Conversion between modes other that ‘L’ and ‘RGB’ needs
conversion into any of these 2 intermediate mode
12
Output
Converting a sample image to Grey Scale
13
Output
14
Networking in Python
▪ Python provides network services for client server model.
15
Networking in Python (contd..)
▪ Syntax for creating a socket:
s = socket.socket (socket_family, socket_type,
protocol=0)
socket_family − AF_UNIX or AF_INET
socket_type − SOCK_STREAM or
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
17
Example - simple server (contd..)
# Listen for incoming connections
sock.listen(1)
connection, client_address = sock.accept()
#Receive command
data = connection.recv(1024)
print(data)
sock.close()
18
Example - simple client
import
socket
import sys
#Send command
client_socket.send('Message to the server')
print('Data sent successfully') 19
Code Snapshot
20
Output
21
Introduction to Raspberry-pi
42
What is Raspberry pi
• Computer in your palm.
• Single-board computer.
• Low cost.
• Easy to access.
43
Specifications
44
Basic architecture
45
Raspberry pi board
46
Start up raspberry pi
47
Raspberry Pi GPIO
• Act as both digital output and digital input.
48
Raspberry Pi pin configuration
49
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
50
51
Operating System
•Official Supported OS :
• Raspbian
• NOOBS
•Some of the third party OS :
• UBUNTU mate
• Snappy Ubuntu core
• Windows 10 core
• Pinet
• Risc OS
52
Raspberry Pi Setup
•Download Raspbian:
• Download latest Raspbian image from raspberry pi official site:
https://www.raspberrypi.org/downloads/
53
Raspberry pi OS setup
54
Basic Initial Configuration
•Enable SSH
•Step1 : Open command prompt and type sudo raspi-config and press enter.
55
Basic Initial Configuration contd.
• Expand file system :
•Step 1: Open command prompt and type sudo raspi-config and press enter.
56
Programming
•Default installed :
• Python
•C
• C++
• Java
• Scratch
• Ruby
•Note : Any language that will compile for ARMv6 can be used with raspberry
pi.
57
Popular Applications
• Media streamer
• Home automation
• Controlling BOT
• VPN
• Light weight web server for IOT
• Tablet computer
58
Topics Covered
▪ Using GPIO pins
▪ Taking pictures using PiCam
2
Blinking LED
▪ Requirement:
▪ Raspberry pi
▪ LED
▪ 100 ohm resistor
▪ Bread board
▪ Jumper cables
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 python-rpi.gpio” to install GPIO library.
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
5
Blinking LED (contd..)
Basic python coding:
6
Blinking LED (contd..)
•Code: #GPIO library
•import RPi.GPIO as GPIO
import time # Set the type of board for pin numbering
GPIO.setmode(GPIO.BOARD) # Set GPIO pin 11as output pin
GPIO.setup(11, GPIO.OUT)
• for i in range (0,5): # Turn on GPIO pin 11
GPIO.output(11,True)
time.sleep(1)
GPIO.output(11,False)
time.sleep(2)
GPIO.output(11,True)
•GPIO.cleanup()
7
Blinking LED (contd..)
EL
PT
N
8
Blinking LED
(contd..)
The LED blinks in a loop with delay
of 1 and 2 seconds.
9
Capture Image using
Raspberry Pi
10
Requirement
▪ Raspberry Pi
▪ Raspberry Pi Camera
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
12
Connection
Boot the Pi once the camera is connected to Pi
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.
14
Configuring Pi for Camera (contd..)
15
Capture Image
▪ Open terminal and enter the command-
raspistill -o image.jpg
16
Capture Image (contd..)
PiCam can also be processed using Python camera module
python-picamera
Python Code:
Import picamera
camera =
picamera.PiCamera()
camera.capture('image.jpg')
17
Capture Image (contd..)
18
Implementation of IOT using
Raspberry-Pi
76
IO
T Internet Of
Things
▪ Creating an interactive environment
▪ Network of devices connectedtogether
2
Sensor
▪ Electronic element
▪ Converts physical quantity into electrical signals
▪ Can be analog or digital
Actuator
▪ Mechanical/Electro-mechanical device
▪ Converts energy into motion
▪ Mainly used to provide controlled motion to other
components
3
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
5
System Overview (contd..)
Requirements
▪ DHT Sensor
▪ 4.7K ohm
resistor
▪ Relay
▪ Jumper wires
▪ Raspberry Pi
▪ Mini fan
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
7
Relay
▪ Mechanical/electromechanical
switch
▪ 3 output terminals (left to right)
▪ NO (normal open):
▪ Common
▪ NC (normal close)
8
Temperature Dependent Auto Cooling System
Sensor interface with Raspberry Pi
9
Temperature Dependent Auto Cooling System (contd..)
10
Temperature Dependent Auto Cooling System (contd..)
11
Program: DHT22 with Pi
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT #importing the Adafruit library
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(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
12
Program: DHT22 interfaced with Raspberry
Pi
Code
Output
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
GPIO.setup(13,GPIO.OUT)
▪ Set the relay pin high when the temperature is greater than 30
if temperature > 30:
GPIO.output(13,0) # Relay is active low
print(‘Relay is on')
sleep(5)
GPIO.output(13,1) # Relay is turned off after delay of 5 seconds
14
Connection: Relay (contd..)
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
16
Connection: Fan (contd..)
17
Result
The fan is switched on whenever
the temperature is above the
threshold value set in the code.
18