Unit 3
Unit 3
UNIT – III
Introduction to Python programming
Introduction to Raspberry Pi
Interfacing Raspberry Pi with basic
peripherals
Implementation of IoT with Raspberry Pi
Why Python?
• Python is an easy to learn, powerful programming language.
• With Python, it is possible to create programs with minimal amount of code.
• It supports interfacing with wide ranging hardware platforms.
Eg: code in Java and Python used for printing the message "Hello World“
Variables and Data Types
Variables
Variables are like containers for storing values. Values in the variables can be
changed.
Values
Consider that variables are like containers for storing information. In the
context of programming, this information is often referred to as value.
Data Type
In programming languages, every value or data has an associated
type to it known as data type.
Some commonly used data types
String
Integer
Float
Boolean
This data type determines how the value or data can be used in the
program.
As per the Python Syntax- True and False are considered as Boolean values. Notice that
both start with a capital letter.
Defining a Variable
A variable gets created when you assign a value to it for the first
time.
We can also define multiple variables at one go. To do that simply write
userAge, userName = 30, ‘Peter’
This is equivalent to
userAge = 30
userName = ‘Peter’
Order of Instructions:
Python executes the code line-by-line.
Example:
Output
In programming, the = sign is known as an assignment sign. It means we are assigning the value
on the right side of the = sign to the variable on the left.
x = 5
y = 10
x = y
print ("x = ", x)
print ("y = ", y)
Output: ?
Inputs and Outputs Basics
input() allows flexibility to take the input from the user. Reads a
line of input as a string.
Working with Strings
String Concatenation: Joining strings together is called string
concatenation.
Example: word=“RAVI”
length=len(word)
print(length)
Output: 4
String Indexing: We can access an individual character in a string using their positions
(which start from 0) .These positions are also called as index.
Example: username = "Ravi"
first_letter = username[0]
print(first_letter)
Output: R
String Slicing
Obtaining a part of a string is called string slicing. Start from the start_index
and stops at end_index .end_index is not included in the slice.
Slicing to End- If end index is not specified, slicing stops at the end of
the string.
message = "Hi Ravi"
part = message[3:]
print(part)
Slicing from Start- If start index is not specified, slicing starts from the
index 0.
Code
a = "Waterfall"
part = a[1:6:3]
print(part)
Output : ar
String Methods
Python has a set of built-in reusable utilities.
They simplify the most commonly performed operations.
isdigit() Syntax:
Gives True if all the characters are digits. Otherwise, False
str_var.isdigit()
strip() Syntax:
Removes all the leading and trailing spaces from a string.
str_var.strip()
mobile = “ 9876543210 “
mobile = mobile. strip(“ “)
print(mobile) Output: 9876543210
Gives a new string after replacing all the occurrences of the old substring
with the new substring.
Code
sentence = "teh cat"
sentence =
sentence.replace("teh","the")
print(sentence)
and
or
Not
Logical AND Operator Gives True if both the Booleans are true else, it gives
False
Examples of Logical AND
Logical OR Operator Gives True if any one of the booleans is true else, it gives
False
Logical NOT Operator Gives the opposite value of the given boolean.
Lists
List a compound data type used to group together other values.
List items need not all have the same type.
Holds an ordered sequence of items
Lists are Mutable
A list contains items separated by commas and enclosed within square brackets.
List methods:
List.append(value) list.insert(index,value)
List1.extend(list2) list.index(value
List.remove(value) list.sort()
#Create List >>>fruits.remove(’mango’)
>>>fruits=[’apple’,’orange’,’banana’,’mango’] >>>fruits
>>>type(fruits) [’apple’, ’orange’, ’banana’, ’pear’]
<type ’list’>
#Inserting an item to a list
#Get Length of List >>>fruits.insert(1,’mango’)
>>>len(fruits) >>>fruits
4 [’apple’, ’mango’, ’orange’, ’banana’, ’pear’]
set_a = {4, 2, 8}
set_b = {1, 2}
diff = set_a - set_b
print(diff)
set_a = {4, 2, 8}
set_b = {1, 2}
symmetric_diff = set_a ^ set_b
print(symmetric_diff)
Dictionaries
• Dictionary is a mapping data type or a kind of hash table
that maps keys to values.
• Keys in a dictionary can be of any data type, though
numbers and strings are commonly used for keys.
• Values in a dictionary can be any data type or object.
#Create a dictionary
>>>student={’name’:’Mary’,’id’:’8776’,’
major’:’CS’}
>>>student
{’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
>>>type(student)
<type ’dict’>
#Get length of a
dictionary #Get all keys in a
>>>len(student) dictionary
3 >>>student.keys()
[’gender’, ’major’, ’name’, ’id’]
#Get the value of a key in
dictionary #Get all values in a
>>>student[’name’] dictionary
’Mary’ >>>student.values()
#Get all items in a [’female’, ’CS’, ’Mary’, ’8776’]
dictionary
>>>student.items() #Add new key-value pair
[(’gender’, ’female’), (’major’, ’CS’), >>>student[’gender’]=’female’
(’name’, ’Mary’), >>>student
(’id’, ’8776’)] {’gender’: ’female’, ’major’: ’CS’,
’name’: ’Mary’, ’id’: ’8776’}
#A value in a dictionary can be another
dictionary
>>>student1={’name’:’David’,’id’:’9876’,’major’:’ECE’}
>>>students={’1’: student,’2’:student1}
>>>students
{’1’:{’gender’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}, ’2’:{’
major’: ’ECE’, ’name’: ’David’, ’id’: ’9876’}}
a = int(input())
counter = 0
while counter < 3:
a = a + 1
print(a)
counter = count
For loop
We can also define the start, stop and step size as range(start,stop,step size). step size
defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
Break Continue
for s in "string": for s in "string":
if s == ‘n': if s == ‘y':
break print continue
(s) print (s)
print “End” print “End”
Modules
Python allows organizing the program code into different
modules which improves the code readability and
management.
A module is a Python file that defines some functionality
in the form of functions or classes.
Modules can be imported using the import keyword.
Modules to be imported must be present in the search path.
Date/Time Operations
# Example 3
s = now.strftime("%-I %p %S")
print('\nExample 3:', s)
# Example 4
s = now.strftime("%-j")
print('\nExample 4:', s)
Functions
A function is a block of code that takes information in (in the form
of parameters), does some computation, and returns a new piece of
information based on the parameter information.
The code block within a function begins after a colon that comes
after the parenthesis enclosing the parameters.
Defining a function
Without return value
def funct_name(arg1, arg2, arg3): # Defining the function
statement 1
statement 2
Output:: Hi!
Functions in Python (contd..)
Example showing function returning
multiple values def greater(x, y):
if x > y:
return x, y
else:
return y, x
print(val)
Output:: (100,10)
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
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.
Example showing Global Variable
g_var = 10
def example():
l_var = 100
print(g_var)
Output:: 10
Example showing Variable Scope
var = 10
def example():
var = 100
print(var)
example()
# calling the function
print(var)
Output:: 100
10
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
for i in range(1,10):
val = random.randint(1,10)
print (val)
Example:
from math import pi
3.14159
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
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!"
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)
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
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
File Read Write Operations (contd..)
PIL is supported till python version 2.7. Pillow supports the 3x version of
python.
Image Read/Write Operations
Reading Image in Python:
PIL: Python Image Library is used to work with image files
Model B - these are the 'full size' boards which include Ethernet and
USB ports
Model A - these are the square shape boards. Consider these a 'lighter'
version of the Raspberry Pi - usually with lower specifications than the
headline Model B, with less USB ports and no Ethernet, however at a
lower price.
Zero - the smallest Raspberry Pis available. Zeros have less computing
grunt than the Model B, but use a lot less power as well. No USB, no
Ethernet.
Specifications
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
Basic Architecture
RAM
ETHERNET USB
4
Raspberry Pi
Raspberry pi GPIO
Raspberry Pi Interfaces
• Serial
The serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins for
communication with serial peripherals.
• SPI
Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for
communicating with one or more peripheral devices.
• I2C
The I2C interface pins on Raspberry Pi allow you to connect hardware modules. I2C
interface allows synchronous data transfer with just two pins - SDA (data line) and
SCL (clock line).
OS Installation –things you need at first
Make sure you already get all of them below:
Raspberry Pi 4 Model B
USB type-C power supply
HDMI cable.
Monitor.
Key board.
Mouse.
microSD card
card reader (for microSD)
network cable (Ethernet RJ45)
laptop or PC
Operating System
Official Supported OS :
• Raspbian
• NOOBS
Some of the third party OS :
• UBUNTU mate
• Snappy Ubuntu core
• Windows 10 core
• Pinet
• Risc OS
Raspberry Pi Setup
Download Raspbian:
• Download latest Raspbian image from raspberry pi official site:
https://www.raspberrypi.org/downloads/
Step 1: Open command prompt and type sudo raspi-config and press
enter.
Sensor Categories
•Controlled by Raspberry Pi
Controlling LED with Raspberry Pi
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
ledPin= 12
GPIO.setup(ledPin, GPIO.OUT)
for i in range(100):
print("LED turning on.")
GPIO.output(ledPin, GPIO.HIGH)
time.sleep(1)
print("LED turning off.")
GPIO.output(ledPin, GPIO.LOW)
time.sleep(1)
Blinking LED (contd..)
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
Blinking LED
(contd..)
Code:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
for i in range (0,5):
GPIO.output(11,True)
time.sleep(1)
GPIO.output(11,False)
time.sleep(2)
GPIO.output(11,True)
GPIO.cleanup()
Blinking LED (contd..)
Requirements:
Raspberry pi
LED
100 ohm resistor
Bread board
Jumper cables
from time import sleep import RPi.GPIO as GPIO
import RPi.GPIO as GPIO import time
GPIO.setmode(GPIO.BCM) GPIO.setmode(GPIO.BCM)
#Switch Pin #Button to GPIO20
GPIO.setup(25, GPIO.IN) GPIO.setup(20, GPIO.IN,
#LED Pin pull_up_down=GPIO.PUD_UP)
GPIO.setup(18, GPIO.OUT) #LED to GPIO24
state=false GPIO.setup(24, GPIO.OUT)
def toggleLED(pin): try:
state = not state while True:
GPIO.output(pin, state) button_state=
while True: GPIO.input(20)
try: if button_state==
if (GPIO.input(25) False:
== True): GPIO.output(24,
toggleLED(pin) True)
sleep(.01) print('Button
except Pressed...’)
KeyboardInterrupt: time.sleep(0.2)
exit() else:
There are two different model of GPIO.setmode(pin numbering)
GPIO.output(24,
•GPIO.BOARD : using board numbering system (ex: pin 12)
False)
•GPIO.BCM : using BCM numbers (ex : GPIO 18)
except:
GPIO.cleanup()
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
Ethernet port and HDMI port
Connection
raspistill -o image.jpg
This will store the image as ‘image.jpg’
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')
Capture Image (contd..)
Implementation of IoT with
Raspberry Pi
Block diagram of an IoT Device
IOT - Internet of Things
Creating an interactive environment
Network of devices connected together
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
Basic Raspberry Pi –Sensors
What are Sensors ?
•Add almost-human sensing capabilities
•Take real-world events
•Convert them to analog or digital signals
•Read by Raspberry Pi
Basic Raspberry Pi –Sensors
Sensor Categories
Sensor Categories
•Controlled by Raspberry Pi
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
Temperature Dependent Auto Cooling System
System Overview (contd..)
Requirements
DHT Sensor
4.7K ohm resistor
Relay
Jumper wires
Raspberry Pi
Mini fan
DHT Sensor
Digital Humidity and Temperature Sensor (DHT)
PIN 1, 2, 3, 4 (from left to right)
o PIN 1- 3.3V-5V Power supply
o PIN 2- Data
o PIN 3- Null
o PIN 4- Ground
Relay
Mechanical/electromechanical switch
3 output terminals (left to right)
NO (normal open):
Common
NC (normal close)
Sensor interface with Raspberry Pi
Connect pin 1 of DHT sensor to the 3.3V pin of Raspberry Pi
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
Connection: Relay (contd..)
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.