0% found this document useful (0 votes)
5 views92 pages

CSE Iot Unit 3

The document provides an introduction to Python programming, highlighting its versatility, ease of use, and support for various data types, control statements, and functions. It also covers file operations, exception handling, and networking capabilities in Python, along with an overview of Raspberry Pi, its setup, and applications. Additionally, it includes practical examples such as blinking an LED and capturing images using Raspberry Pi.

Uploaded by

vinayyroy46
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)
5 views92 pages

CSE Iot Unit 3

The document provides an introduction to Python programming, highlighting its versatility, ease of use, and support for various data types, control statements, and functions. It also covers file operations, exception handling, and networking capabilities in Python, along with an overview of Raspberry Pi, its setup, and applications. Additionally, it includes practical examples such as blinking an LED and capturing images using Raspberry Pi.

Uploaded by

vinayyroy46
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/ 92

Introduction to Python

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 + “!”)

example (“Hi”) # Calling the function

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

val = greater(10, 100)


print(val)

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

using #To access functions and values


module_name.var with ‘var’ in the module

16
Modules in Python (contd..)
▪ Example:
import random

for i in range(1,10):
val =
random.randint(1,10)
print (val)

Output:: varies with each execution

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()

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
with open(“data.txt","w") as file:
file.write(“writing to the text file”)
file.close()

5
File Read Write Operations code + image
with open("PythonProgram.txt","w") as file:
file.write("Writing data")
file.close()

with open("PythonProgram.txt","r") as file:


f=file.read()
print('Reading from the file\n')
print (f)
file.close()

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 = file = "output.csv"
csv.reader(csv_file) with open(file, "w") as csv_file:
print("Reading from the CSV File\n") writer = csv.writer(csv_file, delimiter=',')
for row in reader: print("Writing CSV")
print(" ".join(row)) for line in data:
csv_file.close() writer.writerow(line)
csv_file.close()

7
File Read Write Operations (contd..)

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.

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=Image.open(image_name)

▪ Display the image


image.show()

10
Image Read/Write Operations (contd..)
Resize(): Resizes the image to the specified size
image.resize(255,255)

Rotate(): Rotates the image to the specified degrees, counter clockwise


image.rotate(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(image.format, image.size, image.mode)

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.

▪ 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.

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

SOCK_DGRAM protocol − default ‘0’.

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 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port


server_address = ('10.14.88.82', 2017)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

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

# Create a TCP/IP socket


client_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)

#Connect to Listener socket


client_socket.connect(("10.14.88.82", 2017))
print>>sys.stderr,'Connection Established'

#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.

• Output: turn a GPIO pin high or low.

• Input: detect a GPIO pin high or low

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/

• Unzip the file and end up with an .img file.


•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

53
Raspberry pi OS setup

54
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

55
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.

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:

▪ Open terminal enter the command


sudo nano filename.py
▪ 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

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

▪ This will store the image as ‘image.jpg’

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 =
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

▪ 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

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)

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
https://github.com/adafruit/Adafruit_Python_DHT.g...
▪ Go to folder Adafruit_Python_DHT
cd Adafruit_Python_DHT
▪ Install the library
sudo python setup.py install

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

humidity, temperature = Adafruit_DHT.read_retry(sensor,17)


print ('Temp={0:0.1f}*C humidity={1:0.1f}%'.format(temperature, humidity))

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.

Notice the relay indicator turned


on.

18

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy