0% found this document useful (0 votes)
979 views74 pages

FIoT Unit 03

This document provides an introduction to Python programming and the Raspberry Pi. It covers Python data types, control statements, functions, modules, and exception handling. It also discusses Raspberry Pi specifications and interfacing it with basic peripherals like blinking LEDs and capturing images. Finally, it describes implementing an IoT project with Raspberry Pi to monitor temperature using a DHT sensor and control a fan through a relay.
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)
979 views74 pages

FIoT Unit 03

This document provides an introduction to Python programming and the Raspberry Pi. It covers Python data types, control statements, functions, modules, and exception handling. It also discusses Raspberry Pi specifications and interfacing it with basic peripherals like blinking LEDs and capturing images. Finally, it describes implementing an IoT project with Raspberry Pi to monitor temperature using a DHT sensor and control a fan through a relay.
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/ 74

Unit-03: Introduction to Python and Raspberry Pi

EC600OE: Fundamentals of Internet Of Things

Dr. Mohammad Fayazur Rahaman


Associate Professor, [email protected]

Dept. of Electronics and Communications Engineering,


Mahatma Gandhi Institute of Technology, Gandipet, Hyderabad-75

B.Tech. ECE III Year II Semester (R18)


2022 - 2023 1 / 74
Unit-03: Introduction to Python and Raspberry Pi [1]
1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi
1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope
4.1 Internet of Things
1.2 Modules in Python
4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling
1.6 Image Read Write System
1.7 Networking in Python 4.3.1 Program: DHT22 with Pi
4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

2 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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

• Programming languages are “high level”, • Python is basically an interpreted lan-


for humans to understand guage
• Computers need “lower level” instruc- ◦ Load the Python interpreter
tions ◦ Send Python commands to the inter-
• Compiler: Translates high level pro- preter to be executed
gramming language to machine level in- ◦ Easy to interactively explore language
structions, generates “executable” code features
• Interpreter: Itself a program that runs ◦ Can load complex programs from files
and directly “understands” high level from filename import *
programming language

5 / 74
Starting with Python:
• Simple printing statement at the python interpreter prompt,

1 >>> print("Hi, Welcome to python ! ")


2 Hi, Welcome to python !
• To indicate different blocks of code, it follows rigid indentation.

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 x,y,z = 10,10.2, 2+3j


II. Boolean

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

• Normal arithmetic operations: +,-,*,/


◦ Note that / always produces a float
◦ 7/3.5 is 2.0, 7/2 is 3.5
• Quotient and remainder: // and %
◦ 9//5 is 1, 9%5 is 4
• Exponentiation: **
◦ 3**4 is 81

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:

1 for s in "string": 1 for s in "string":


2 if s=='n': 2 if s=='i':
3 break 3 continue
4 print(s) 4 print(s)
5 print("End") 5 print("End")

11 / 74
Functions in Python
Defining a function
I. Without return value:

1 def func_name(arg1, arg2, arg3):


2 statement 1
3 statement 2
II. With return value:

1 def func_name(arg1, arg2, arg3):


2 statement 1
3 statement 2
4 return x # Returning the value
12 / 74
III. Calling a function
1 def example(str):
2 print(str + '!')
3

4 example("Hi") # Calling the function


5 Output: Hi!
IV. Function returning multiple values
1 def greater(x,y):
2 if x>y:
3 return x,y
4 else:
5 return y,x
6

7 val = greater(10,100) # Calling the function


8 print(val)
9 #Output: (100,10)
13 / 74
Variable Scope
I. Global Variable: These are the vari- II. Local Variables: These are the ones
ables declared out of any function , that are declared inside a function.
but can be accessed inside as well as
outside the function. 1 var = 10
2 def example():
1 g_var = 10 3 var = 100
2 def example(): 4 print(var)
3 l_var = 100 5

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 ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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:

1 #At the top of the code


2 import module_name
3 #To access functions and values with ‘var’ in the module
4 module_name.var

• 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:

1 from math import pi


2 print (pi)
3

4 #Output:: 3.14159

17 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

18 / 74
Exception Handling

• An error that is generated during execu- • Example:


tion of a program, is termed as excep-
tion. Syntax: 1 while True:
2 try:
1 try: 3 n = input("Enter an integer:")
2 statements 4 n = int (n)
3 except _Exception_: 5 print("It is an integer!")
4 statements 6 break
5 else: 7 except ValueError:
6 statements 8 print("Not a valid integer!")
9 print("End")

19 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

20 / 74
Example Code
1 x = int (input("Enter a number >1 : "))
2

3 def prime (num):


4 if num > 1:
5 for i in range(2,num):
6 if (num % i) == 0:
7 print (num,"is not a prime number")
8 print (i," is a factor of ",num)
9 return
0 print(num," is a prime number")
1 else:
2 print(num," is not >1")
3

4 prime (x)
21 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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:

1 with open("file_path","w") as file:


2 file.write("hello world")

• Is equivalent to:

1 file = open('file_path', 'w')


2 try:
3 file.write('hello world')
4 finally:
5 file.close()

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)

• Result: printed to terminal

1 [ '26.1', '36.2']
2 [ '27.0', '37.2']
3 [ '25.1', '35.1']

27 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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 from PIL import Image

• Open an image file

1 image=Image.open(image_name)

• Display the image

1 image.show()

29 / 74
• Resize(): Resizes the image to the specified size

1 image.resize(255,255)

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

1 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

1 print(image.format, image.size, image.mode)

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

1 from PIL import Image


2 im = Image.open("mgit.png")
3 im.show()
4 grey_image = im.convert('L')
5 grey_image.show()
6 grey_image.save('Greymgit.png')

31 / 74
Output

32 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

33 / 74
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.

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 ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

38 / 74
Raspberry Pi Specifications

What is Raspberry Pi?


• Computer in your palm. • Low cost.
• Single-board computer. • Easy to access. 39 / 74
The Raspberry Pi 4 Model B, has the • 2-lane MIPI DSI display port
following specifications: • 2-lane MIPI CSI camera port
• Broadcom BCM2711, quad-core Cortex- • 4-pole stereo audio and composite video
A72 (ARM v8) 64-bit SoC @ 1.5GHz port
• 2GB, 4GB, or 8GB LPDDR4-3200 • H.265 (4kp60 decode), H264 (1080p60
SDRAM (depending on model) decode, 1080p30 encode)
• Dual-band (2.4GHz and 5.0GHz) IEEE • OpenGL ES 3.0 graphics
802.11b/g/n/ac wireless LAN • Micro-SD card slot for loading operating
• Bluetooth 5.0, BLE system and data storage
• Gigabit Ethernet • 5V DC via USB-C connector (minimum
• 2 USB 3.0 ports; 2 USB 2.0 ports. 3A*)
• Raspberry Pi standard 40 pin GPIO • 5V DC via GPIO header (minimum 3A*)
header (fully backwards compatible with • Power over Ethernet (PoE) enabled (re-
previous boards) quires separate PoE HAT)
• 2 micro-HDMI ports (up to 4kp60 sup- • Operating temperature: 0 – 50 degrees
ported) C ambient
40 / 74
Some of the factors to consider when selecting a Raspberry Pi model are:
I. Processing Power: The higher the processing power, the more capable the
Raspberry Pi will be of running complex programs and applications. For
CPU-intensive tasks, such as image or video processing, a model with a more
powerful processor, such as the Raspberry Pi 4, is recommended.
II. Memory: The more RAM a Raspberry Pi has, the more efficient it will be at
running multiple applications simultaneously. For projects that require running
multiple applications or large datasets, a model with more RAM, such as the
Raspberry Pi 4 with 8GB RAM, is recommended.
III. Connectivity: Depending on the project, connectivity options such as Wi-Fi,
Bluetooth, and Ethernet may be important. Some models, such as the Raspberry
Pi 3 and 4, have built-in Wi-Fi and Bluetooth capabilities, while others, such as
the Raspberry Pi Zero, require additional hardware.
IV. Cost: Different models of Raspberry Pi are available at different price points.
Generally, the newer and more powerful models are more expensive than older
and less powerful models.
V. Size: Depending on the project, size may be an important factor to consider.
Smaller models, such as the Raspberry Pi Zero, are more portable and may be 41 / 74
Basic Architecture

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 ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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 ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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

4 # Set the type of pin numbering (BCM or BOARD)


5 GPIO.setmode(GPIO.BCM)
6 GPIO.setup(17, GPIO.OUT)
7

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

Output: The LED blinks in a loop with delay of 1 second


52 / 74
53 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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 ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

58 / 74
Internet of Things

IoT: electrical signals


• Creating an interactive environ- • Can be analog or digital
ment Actuator:
• Network of devices connected to- • Mechanical/Electro-mechanical
gether device
Sensor: • Converts energy into motion
• Electronic element • Mainly used to provide controlled
• Converts physical quantity into motion to other components

59 / 74
Where are we ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

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 ?

1. Introduction to Python programming [1, 4] 2.2 Basic Setup for Raspberry Pi


1.1 Introduction 3. Interfacing Raspberry Pi with basic peripherals
1.1.1 Data Types 3.1 Blinking LED
1.1.2 Controlling Statements 3.2 Capture Image using Raspberry Pi
1.1.3 Functions in Python 4. Implementation of IoT with Raspberry Pi
1.1.4 Variable Scope 4.1 Internet of Things
1.2 Modules in Python 4.2 System Overview
1.3 Exception Handling 4.2.1 DHT Sensor
1.4 Example Code: To check prime 4.2.2 Relay
1.5 File Read Write 4.3 Temperature Dependent Auto Cooling System
1.6 Image Read Write 4.3.1 Program: DHT22 with Pi
1.7 Networking in Python 4.3.2 Connection: Relay
2. Introduction to Raspberry Pi 4.3.3 Connection: Fan
2.1 Raspberry Pi Specifications 4.3.4 Result

64 / 74
Temperature Dependent Auto Cooling System

Sensor interface with Pi


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

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

Adafruit library for DHT22 sensor:


• 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

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

1 humidity, temp = Adafruit_DHT.read_retry(sensor, 17)


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

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

3 if temperature > 30:


4 GPIO.output(13,0) # Relay is active low
5 print('Relay is on')
6 sleep(5)
7 GPIO.output(13,1) # Relay is turned off after delay of 5 seconds

69 / 74
70 / 74
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

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

[2] A. Bahga and V. Madisetti, Internet of Things: A Hands-on Approach.

[3] K. K. Terokarvinen and V. Valtokari, Make Sensors.


1st Edition, Maker media, 2014.

[4] P. M. Mukund, “Nptel: Programming, data structures and algorithms in python,”


2019.
https://www.youtube.com/playlist?list=PLyqSpQzTE6M_
Fu6l8irVwXkUyC9Gwqr6_ [Accessed: Feb 2023].
73 / 74
Thank you

74 / 74

You might also like