0% found this document useful (0 votes)
11 views130 pages

Unit 3

This document provides an introduction to Python programming and its applications with Raspberry Pi, including basic concepts like variables, data types, and string manipulation. It covers various programming constructs such as lists, tuples, sets, and dictionaries, along with control statements and loops. The document also highlights Python's ease of use and its capability to interface with hardware for IoT implementations.

Uploaded by

tejthunder60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views130 pages

Unit 3

This document provides an introduction to Python programming and its applications with Raspberry Pi, including basic concepts like variables, data types, and string manipulation. It covers various programming constructs such as lists, tuples, sets, and dictionaries, along with control statements and loops. The document also highlights Python's ease of use and its capability to interface with hardware for IoT implementations.

Uploaded by

tejthunder60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 130

CONTD…

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.

Example: mathematical operations can be done on Integer and Float


String
A String is a stream of characters enclosed within quotes.
Stream of Characters
Capital Letters ( A – Z ) or Small Letters ( a – z ) or Digits ( 0 – 9 ) or
Special Characters (~ ! @ # $ % ^ . ?,) or Space
Some Examples:
1. "Hello World!"
2."1234"
Integer
All whole numbers (positive, negative and zero) without any fractional part
come under Integers.
Examples : ...-3, -2, -1, 0, 1, 2, 3,...
Float
Any number with a decimal point- 24.3, 345.210, -321.86
Boolean
In a general sense, anything that can take one of two possible values is considered a Boolean.
Examples: the data that can take values like
True or False Yes or No 0 or 1 On or Off etc..

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.

Variable name enclosed in quotes will


print variable rather than the value in
it.

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

NameError: name ‘age’ is not defined

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: a=“Hello”+ “ “ +”world”


print(a)

Output: Hello world

String Repetition- * operator is used for repeating strings any


number of times as
required.
Length of String

len() returns the number of characters in a


given string.

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.

Code: variable_name=[Start: End]

Example:1 message = "Hi Ravi"


part = message[3:7]
print(part)
Output: Ravi

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.

message = "Hi Ravi"


part = message[:2]
print(part)
Extended Slicing and String Methods
Extended Slicing
Syntax:
variable[start_index:end_index:step]

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

We can also specify characters that need to be removed.


name = "Ravi."
name = name.strip(“.”)
print(name)
Output: Ravi
Strip - Multiple Characters
Removes all spaces, comma(,) and full stop(.) that lead or
trail the string.
name = ",... Ravi "
Code:
name = name.strip(", .")
print(name)
Output : Ravi
Replace Syntax:
str_var.replace(old,new)

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)

lower() , upper(),startswith(),endswith() more...


Type conversions
1. int() -> Converts to integer data
type
2. float() -> Converts to float data
type
3. str() -> Converts to string data
type
4. bool() -> Converts to Boolean data
type
#Convert to long
>>>long(b)
#Convert to string 2013L
>>>a=10000
#Convert to list
>>>str(a)
>>>s="aeiou"
’10000’
>>>list(s)
#Convert to int
[’a’, ’e’, ’i’, ’o’, ’u’]
>>>b="2013" #Convert to set
>>>int(b) >>>x=[’mango’,’apple’,’banana’,’mango’,
2013 ’banana’]
#Convert to float >>>set(x)
>>>float(b) set([’mango’, ’apple’, ’banana’])
2013.0
Basic
Operators
Suppose x = 5, y = 2
 Addition: x + y = 7
 Subtraction: x - y = 3
 Multiplication: x*y = 10
 Division: x/y = 2.5
 Floor Division: x//y = 2 (integral part of
quotient)
 Modulus: x%y = 1 (Gives the remainder)
 Exponent: x**y = 25 (5 to the power of 2)
Logical Operators
The logical operators are used to perform logical operations on Boolean values.
Gives True or False as the result.
Following are the logical operators

 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’]

#Access List Elements #Combining lists


>>>fruits[1] >>>vegetables=[’potato’,’carrot’,’onion’,’beans’,’r
’orange’ adish’]
>>>fruits[1:3] >>>vegetables
[’orange’, ’banana’] [’potato’, ’carrot’, ’onion’, ’beans’, ’radish’]
>>>fruits[1:] >>>eatables=fruits+vegetables
[’orange’, ’banana’, ’mango’] >>>eatables
[’apple’,’mango’,’orange’,’banana’,’pear’, potato’,
#Appending an item to a list ’carrot’, ’onion’, ’beans’, ’radish’]
>>>fruits.append(’pear’)
>>>fruits
[’apple’, ’orange’, ’banana’, ’mango’, ’pear’]
#Mixed data types in a list
>>>mixed=[’data’,5,100.1,8287398L] #Lists can be nested
>>>type(mixed) >>>nested=[fruits,vegetables]
<type ’list’> >>>nested
>>>type(mixed[0]) [[’apple’, ’mango’, ’orange’, ’banana’, ’pear’],
<type ’str’> [’potato’, ’carrot’, ’onion’, ’beans’, ’radish’]]
>>>type(mixed[1])
<type ’int’>
>>>type(mixed[2])
<type ’float’>
>>>type(mixed[3])
<type ’long’>

#Change individual elements of a


list
>>>mixed[0]=mixed[0]+" items"
>>>mixed[1]=mixed[1]+1
>>>mixed[2]=mixed[2]+0.05
>>>mixed
[’data items’, 6, 100.14999999999999,
8287398L]
Tuples
 A tuple is a sequence data type that is similar to the list.
 Holds an ordered sequence of items
 Tuples are immutable
 A tuple consists of a number of values separated by
commas and enclosed
within parentheses.
 Unlike lists, the elements of tuples cannot be changed, so
tuples can be thought of as read-only lists.
>>>fruits[0]
#Create a Tuple ’apple’
>>>fruits=("apple","mango", >>>fruits[:2]
"banana","pineapple") (’apple’, ’mango’)
>>>fruits
(’apple’, ’mango’, ’banana’, ’pineapple’) #Combining tuples
>>>type(fruits) >>>vegetables=(’potato’,’carrot’,’onion’,’radi
<type ’tuple’> sh’)
>>>eatables=fruits+vegetables
#Get length of tuple >>>eatables
>>>len(fruits) (’apple’, ’mango’, ’banana’, ’pineapple’,
4 ’potato’, ’carrot’, ’onion’, ’radish’)

#Get an element from a tuple


Sets
 Unordered collection of items.
 Every set element is Unique (no
duplicates)
 Must be immutable
set_a = {4, 2, 8} set_a = {4, 2, 8}
set_b = {1, 2} list_a = [1, 2]
union = set_a | union = set_a.union(list_a)
set_b print(union)
print(union)
set_a = {4, 2, 8}
set_b = {1, 2}
intersection = set_a & set_b
print(intersection)

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’}}

#Check if dictionary has a key


>>>student.has_key(’name’)
True
>>>student.has_key(’grade’)
False
Controlling Statements
Nested Conditional
Statements

Nested Condition in Else


Block
>>>a = 25**5 >>>if a>10000:
>>>if a>10000: if a<1000000:
print "More" print "Between 10k and 100k"
else: else:
print "Less" print "More than 100k"
More elif a==10000:
print "Equal to 10k"
>>>s="Hello World" else:
>>>if "World" in s: print "Less than 10k"
s=s+"!" More than 100k
print s
Hello World! >>>student={’name’:’Mary’,’id’:’87
76’}
>>>if not student.has_key(’major’):
student[’major’]=’CS’
>>>student
{’major’: ’CS’, ’name’: ’Mary’, ’id’:
’8776’}
While loop

a = int(input())
counter = 0
while counter < 3:
a = a + 1
print(a)
counter = count
For loop

word = "Python" for number in range


for each_char in word: (1,10)
print(each_char) print(number)
The range() function
We can generate a sequence of numbers using range() function.

range(10) will generate numbers from 0 to 9 (10 numbers).

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

The following example will clarify this.

# Output: range(0, 10) print(range(10))


# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
Controlling Statements (contd..)

 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

• Python provides several functions for date and time access


and conversions.
• The datetime module allows manipulating date and time in
several ways.
• The time module in Python provides various time-related
functions.
# strftime() function

from datetime import datetime


as dt Without formatting 2019-12-17
18:21:39.211378
# Getting current date and time
now = dt.now()
print("Without formatting", now) Example 1: Tue-12-19

# Example 1 Example 2: Tuesday-12-2019


s = now.strftime("%a %m %y")
print('\nExample 1:', s)
Example 3: 6 PM 39
# Example 2
s = now.strftime("%A %-m %Y") Example 4: 351
print('\nExample 2:', s)

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

 A function in Python is a block of code that begins with the keyword


def followed by the function name and parentheses. The
function parameters are enclosed within the parenthesis.

 The code block within a function begins after a colon that comes
after the parenthesis enclosing the parameters.

 The first statement of the function body can optionally be a


documentation string or docstring.
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


def funct_name(arg1, # Defining the function
arg2, arg3):
statement 1 # Returning the value
statement 2
return x
Functions in Python
 Calling a function
def example (str):
print (str + “!”)

example (“Hi”) # Calling the function

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

val = greater(10, 100)

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)

example() # calling the function

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

#To access functions and values


using module_name.var
with ‘var’ in the module
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


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

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’)
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()
File Read Write Operations

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()
File Read Write Operations (contd..)

Comma Separated Values


Files
 Write:
CSV module supported for CSV files

Read: data = ["1,2,3,4,5,6,7,8,9".split(",")]


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


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
Output
Converting a sample image to Grey Scale
Output
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.
Introduction to Raspberry Pi
What is Raspberry Pi?
• Computer in your palm.
• Single-board computer.
• Low cost.
• Easy to access.
 Raspberry Pi is a low-cost mini-computer with the physical size of a credit card.
 Raspberry Pi runs various flavors of Linux and can perform almost all tasks that a
normal desktop computer can do.
 Raspberry Pi also allows interfacing sensors and actuators through the general purpose
I/O pins.
 Since Raspberry Pi runs Linux operating system, it supports Python "out of the box".
Raspberry Pi come in three different formats:

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

I/O CPU/GPU USB HUB

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/

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

Easily Install Windows 10 On The Raspberry Pi 4 Or Raspberry Pi 3! Real Windows 10 On ARM!


OS Installation
• We need to download a tool to flash OS image to SD card
Example :Rufus (Windows only) or balenaEtcher (Windows /
macOS / Linux)

• Flash .img file into your SD card


• (You need a SD card reader to help you complete this step.)

OS Installation –SSH/VNC Connect


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”
• Browse the “Image File”(Raspbian image)
• Write
Raspberry Pi OS Setup
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


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.


Programming
Default installed :
• Python
•C
• C++
• Java
• Scratch
• Ruby
Note : Any language that will compile for ARMv6 can be used with
raspberry pi.
Popular Applications
•Media streamer
•Home automation
•Controlling BOT
•VPN
•Light weight web server for IOT
•Tablet computer
Interfacing Raspberry Pi with basic
peripherals
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

• Temperature / Humidity / Air Pressure / Gas


• Motion Sensors
• Navigation Modules
• Wireless / Infrared (IR) / Bluetooth
• Analogue Sensors• Current Supply
• Displays
• Other Modules, Components and Sensors
Basic Raspberry Pi –Actuators
What are Actuators ?
•Convert an electrical signal into a corresponding physical quantity
Example: movement, force, sound etc.

•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..)

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

The LED blinks in a loop with delay of 1


and 2 seconds.
Raspberry Pi Example:
Interfacing LED and switch with Raspberry Pi

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

Boot the Pi once the camera is connected to Pi


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.
Configuring Pi for Camera (contd..)
Capture Image
 Open terminal and enter the command-

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

sudo apt-get install 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

• Temperature / Humidity / Air Pressure / Gas


• Motion Sensors
• Navigation Modules
• Wireless / Infrared (IR) / Bluetooth
• Analogue Sensors• Current Supply
• Displays
• Other Modules, Components and Sensors
Basic Raspberry Pi –Sensors

Sensor Categories

• Temperature / Humidity / Air Pressure / Gas


• Motion Sensors
• Navigation Modules
• Wireless / Infrared (IR) / Bluetooth
• Analogue Sensors• Current Supply
• Displays
• Other Modules, Components and Sensors
Basic Raspberry Pi –Actuators
What are Actuators ?
•Convert an electrical signal into a corresponding physical quantity
Example: movement, force, sound etc.

•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

 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


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)
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
Program: DHT22 with Pi
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
sensor = Adafruit_DHT.AM2302
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))
Program: DHT22 interfaced with Raspberry
Pi
Code Output
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
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.

 Run the existing code. The fan should operate when


Connection: Fan (contd..)
Result
• The fan is switched on whenever the temperature is above the
threshold value set in the code.

• Notice the relay indicator turned on.

You might also like