FIoT Unit 03
FIoT Unit 03
2 / 74
Where are we ?
3 / 74
Introduction
Why Python? a strong backbone to build large
• Python is a versatile language applications.
which is easy to script and easy Python IDE:
to read. • Python IDE is a free and open
• It doesn’t support strict rules for source software that is used to
syntax. write codes, integrate several
• Its installation comes with inte- modules and libraries.
grated development environment • It is available for installation into
for programming. PC with Windows, Linux and
• It supports interfacing with wide Mac.
ranging hardware platforms. • Examples: Spyder, PyCharm, etc.
• With open-source nature, it forms
4 / 74
Interpreters vs compilers
5 / 74
Starting with Python:
• Simple printing statement at the python interpreter prompt,
1 if True:
2 print("Correct")
3 else:
4 print("Error")
6 / 74
Data Types
The following are some of the data types in Python:
I. Numbers
1 b = True
III. String
1 x = 'This is Python'
2 print(x) #This is Python
3 print(x[0]) #T
4 print(x[2:4]) #is
7 / 74
IV. List
1 x = [10,10.2,'python', 2+3j]
V. Tuple
1 x = (2,4,'python')
VI. Set
1 s = {'item', 'k', 2}
VII. Dictionary
1 d = {1:'item', 'k':2}
8 / 74
Operations on numbers
9 / 74
Controlling Statements
I. If-Elif-Else: II. While:
1 if(cond.): 1 while(cond.):
2 statement 1 2 statement 1
3 statement 2 3 statement 2
4 elif(cond.): III. For:
5 statement 1
6 statement 2 1 x=[1,2,3,4]
7 else: 2 for i in x:
8 statement 1 3 statement 1
9 statement 2 4 statement 2
10 / 74
IV. Break: V. Continue:
11 / 74
Functions in Python
Defining a function
I. Without return value:
4 print(g_var) 6 example()
5 7 print(var)
6 example() 8 #Output:
7 #Output: 10 9 #100
10 #10
14 / 74
Where are we ?
15 / 74
Modules in Python
• Any segment of code fulfilling a particular task that can be used commonly by
everyone is termed as a module. Syntax:
• Example:
1 import random
2 for i in range(1,10):
3 val = random.randint(1,10)
4 print(val)
5 #Output: varies with each execution
16 / 74
• We can also access only a particular function from a module
• Example:
4 #Output:: 3.14159
17 / 74
Where are we ?
18 / 74
Exception Handling
19 / 74
Where are we ?
20 / 74
Example Code
1 x = int (input("Enter a number >1 : "))
2
4 prime (x)
21 / 74
Where are we ?
22 / 74
File Read Write
• Python allows you to read and I. Opening a file:
write files • Open() function is used to open
• No separate module or library re- a file, returns a file object
quired
• Three basic steps 1 open(file_name, mode)
I. Open a file
II. Read/Write • Mode: Four basic modes to open
III. Close the file a file
◦ r: read mode
◦ w: write mode
◦ a: appen mode
◦ r+: both read and write mode
23 / 74
II. Read/Write from/to a file:
III. Closing a file:
• Read(): Reads from a file • Close(): This is done to ensure
that the file is free to be used by
1 file=open("data.txt", "r") other resources
2 file.read()
• Write(): Writes to a file 1 file.close()
1 file=open("data.txt", "w")
2 file.write("Hello World")
24 / 74
• 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
• Using With to access a file:
• Is equivalent to:
25 / 74
• Comma separated values files: csv module support for CSV files:
• Write
1 import csv
2 data = [ (26.1, 36.2), (27.0, 37.2), (25.1, 35.1)]
3
4 file = "output.csv"
5 with open(file, 'w') as csv_file :
6 writer = csv.writer(csv_file, delimiter=":")
7 for line in data:
8 writer.writerow(line)
• Result: ’output.csv’ file created with content
1 26.1:36.2
2 27.0:37.2
3 25.1:35.1
26 / 74
• Read
1 import csv
2 file = "output.csv"
3 with open(file, 'r') as csv_file :
4 reader = csv.reader(csv_file, delimiter=":")
5 for line in reader:
6 print(line)
1 [ '26.1', '36.2']
2 [ '27.0', '37.2']
3 [ '25.1', '35.1']
27 / 74
Where are we ?
28 / 74
Image Read/Write Operations
• Python supports PIL (Python Image Library) for image related operations
• Install PIL through PIP : sudo pip install pillow
• Reading Image in Python:
1 image=Image.open(image_name)
1 image.show()
29 / 74
• Resize(): Resizes the image to the specified size
1 image.resize(255,255)
1 image.rotate(90)
30 / 74
• Any image can be converted from one mode to ‘L’ or ‘RGB’ mode
1 conv_image=image.convert('L')
• Conversion between modes other that ‘L’ and ‘RGB’ needs conversion into any of
these 2 intermediate mode
• Converting a sample image to Grey Scale
31 / 74
Output
32 / 74
Where are we ?
33 / 74
Networking in Python
34 / 74
Basic steps involved in Python Socket programming are:
I. Creating a Socket: The socket.socket() method is used to specify the
address family (IPv4 or IPv6) and the socket type (stream or datagram)
II. Binding a Socket: The bind() method is used to specify the address and port
to bind to
III. Listening for connections: A server application need to start listening for
incoming connections using listen() method
IV. Accepting a connection:
• When a client connects to the server using connect() method ,
• the server uses accept() method to accept the client connection
V. Sending and receiving data: Once the connection is established, data can be
sent and received using send() and recv() methods
VI. Closing the connection and socket: After the data transfer, the connection
and the socket resources are freed using the close() method
35 / 74
• Simple Echo Server Example: The socket waits until a client connects to the
port, and then returns data received over the connection object
1 import socket
2
3 HOST = '127.0.0.1'
4 PORT = 50007
5 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
6 s.bind((HOST, PORT))
7 s.listen(1)
8 conn, addr = s.accept()
9 with conn:
10 print('Connected by', addr)
11 while True:
12 data = conn.recv(1024)
13 if not data: break
14 conn.sendall(data)
36 / 74
• Simple Client Example: The socket connects to the server, sends a message and
receives a message
1 import socket
2
3 HOST = '127.0.0.1'
4 PORT = 50007
5 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
6 s.connect((HOST, PORT))
7 s.sendall(b'Hello, world')
8 data = s.recv(1024)
9 print('Received', repr(data))
37 / 74
Where are we ?
38 / 74
Raspberry Pi Specifications
42 / 74
Raspberry Pi GPIO: The Raspberry Pi 4 Model B has 40 GPIO (General Purpose
Input Output) pins arranged in a 2x20 configuration. These pins can be used for digital
input/output or for communication with various sensors, actuators, and other devices.
43 / 74
The GPIO pins on the Raspberry Pi 4 V. UART Pins: These pins are used
Model B are grouped into several for Universal Asynchronous Receiver-
categories, including: Transmitter (UART) communica-
I. Power and Ground Pins: These tion.
pins provide 5V and 3.3V power, as VI. PWM Pins: These pins are used
well as ground connections for the for Pulse Width Modulation (PWM)
board. output.
II. GPIO Pins: These are the general- VII. PCM Pins: These pins are used for
purpose input/output pins that can Pulse Code Modulation (PCM) audio
be used for digital input/output or for output.
communication with various devices. VIII. SDIO Pins: These pins are used for
III. SPI Pins: These pins are used for Secure Digital Input Output (SDIO)
Serial Peripheral Interface (SPI) com- communication.
munication. The GPIO pins can be accessed using
IV. I2C Pins: These pins are used for programming languages such as Python
Inter-Integrated Circuit (I2C) com- and C, and various libraries.
munication.
44 / 74
Start up Raspberry Pi
45 / 74
Where are we ?
46 / 74
Basic Setup for Raspberry Pi
Peripherals ◦ Snappy Ubuntu core
i. HDMI cable. ◦ Windows 10 core
ii. Monitor. ◦ Pinet
iii. Key board. ◦ Risc OS
iv. Mouse.
v. 5 volt power adapter for raspberry pi.
vi. LAN cable .
vii. 16 GB micro sd card
Operating System
• Official Supported OS:
◦ Raspbian
◦ NOOBS
• Some of the thrid party OS:
◦ UBUNTU mate
47 / 74
Raspberry Pi Setup ◦ Browse the “Image File”(Raspbian
• Download Raspbian: image)
◦ Download latest Raspbian image ◦ Write
from raspberry pi official site:
https://www.raspberrypi.org/downloads/
◦ 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”
48 / 74
Basic Initial Configuration ◦ Ruby
• Enable VNC/SSH: ◦ Note : Any language that will compile
◦ Step1 : Open command prompt and for ARMv6 can be used with raspberry
type sudo raspi-config and press pi.
enter.
◦ Step2: Navigate to VNC/SSH in the
Advance option.
◦ Step3: Enable VNC/SSH
Programming
• Default installed:
◦ Python
◦ C
◦ C++
◦ Java
◦ Scratch
49 / 74
Where are we ?
50 / 74
Blinking LED
• Requirement: • Connection:
◦ Raspberry pi ◦ Connect the negative terminal of the
◦ LED LED to the ground pin of Pi
◦ 100 ohm resistor ◦ Connect the positive terminal of the
◦ Bread board LED to the output pin of Pi
◦ Jumper cables • Python Coding:
• Installing GPIO library: ◦ Open terminal enter the command
◦ Open terminal sudo nano filename.py
◦ Enter the command “sudo apt-get ◦ This will open the nano editor where
install python-dev” to install you can write your code
python development ◦ Ctrl+O : Writes the code to the file
◦ Enter the command “sudo apt-get ◦ Ctrl+X : Exits the editor
install python-rpi.gpio” to in- ◦ Note: Code can also be write using
stall GPIO library. IDEs like "Thonny Pi" etc.
51 / 74
1 import RPi.GPIO as GPIO # GPIO library
2 import time
3
8 for i in range(0,5):
9 GPIO.output(17, True) # Turn on GPIO pin 17
0 time.sleep(1)
1 GPIO.output(17, False) # Turn off GPIO pin 17
2 time.sleep(1)
3
4 GPIO.cleanup()
54 / 74
Capture Image using Raspberry Pi
Requirement:
• Raspberry Pi
• Raspberry Pi Camera
Raspberry Pi Camera
• Raspberry Pi specific camera module
• Dedicated CSI slot in Pi for connection
• The cable slot is placed between Ether-
net port and HDMI port
Connection
• Boot the Pi once the camera is con-
nected to Pi
55 / 74
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.
56 / 74
Capture Image: Python Code:
• Open terminal and enter the command-
raspistill -o image.jpg
import picamera
• This will store the image as ‘image.jpg’
camera = picamera.PiCamera()
camera.capture('image.jpg')
python-picamera module:
• PiCam can also be processed us-
ing Python camera module python-
picamera "sudo apt-get install
python-picamera"
57 / 74
Where are we ?
58 / 74
Internet of Things
59 / 74
Where are we ?
60 / 74
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
Requirements:
• DHT Sensor
• 4.7K ohm resistor
• Relay
• Jumper wires
• Raspberry Pi
• Mini fan
61 / 74
DHT Sensor:
• Digital Humidity and Tempera-
ture Sensor (DHT)
• PIN1,2,3,4(from left to right)
◦ PIN1-3.3V-5VPower supply
◦ PIN2-Data
◦ PIN3-Null
◦ PIN4-Ground
62 / 74
Relay:
• Mechanical/electromechanical
switch
• 3 output terminals (left to right)
◦ NO (normal open):
◦ Common
◦ NC (normal close)
63 / 74
Where are we ?
64 / 74
Temperature Dependent Auto Cooling System
65 / 74
Relay interface with Raspberry of Raspberry Pi (Here we have
Pi: used pin 7)
• 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 Rasp-
berry Pi
• Connect the input/signal pin of
Relay to the assigned output pin
66 / 74
Program: DHT22 with Pi
67 / 74
1 import RPi.GPIO as GPIO
2 from time import sleep
3 import Adafruit_DHT
4
5 GPIO.setmode(GPIO.BOARD)
6 GPIO.setwarnings(False)
7
8 sensor = Adafruit_DHT.AM2302
9 print("Getting data from the sensor")
0
68 / 74
Program: 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
• Set the relay pin high when the temperature is greater than 30
1 GPIO.setup(13,GPIO.OUT)
2
69 / 74
70 / 74
Connection: Fan
71 / 74
Result
• The fan is switched on whenever the temperature is above the threshold value set in
the code. Notice the relay indicator turned on.
72 / 74
Text Books
[1] P. S. Misra, “Nptel: Introduction to internet of things,” 2019.
https://www.youtube.com/@introductiontointernetofth4217/featured
[Accessed: Feb 2023].
74 / 74