UNIT-3
UNIT-3
Unit-3
Introduction to Python 2
Data types in Python 5
Loop and Control statements 10
Python Functions 14
Exception Handling in Python 17
File Read Write Operations 18
Image Read Write Operations 22
Networking in Python 25
Introduction to Raspberry Pi 27
Basic Architecture of Raspberry Pi 30
Programming with Raspberry Pi
Blinking LED 34
Interfacing of LED and Switch with Raspberry Pi 36
Implementation IOT with Raspberry Pi 37
Program for interfacing with sensors and actuators 40
2
INTRODUCTION TO PYTHON
What is Python?
For example, x = 10
Here, x can be anything such as String, int, etc.
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very
quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.
Python Features
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to
learn the language as compared to other languages like C, C#, Javascript, Java, etc. It
is very easy to code in python language and anybody can learn python basics in a
few hours or days. It is also a developer-friendly language.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, objects encapsulation,
etc.
5. High-Level Language:
Python is a high-level language. When we write programs in
python, we do not need to remember the system architecture, nor
do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python
code into C or C++ language and also we can compile that code in
C/C++ language.
9. Interpreted Language:
Python is an Interpreted Language because Python code is
executed line by line at a time. like other languages C, C++, Java,
etc. there is no need to compile python code this makes it easier to
debug our code. The source code of python is converted into an
immediate form called bytecode.
Python IDE is a free and open source software that is used to write codes,
integrate several modules and libraries.
Numbers
String
List
Tuple
Dictionary
Python sets the variable type based on the value that is assigned to it.
Unlike more riggers languages, Python will change the variable type if the
variable value is set to another value. For example:
Numbers
Python numbers variables are created by the standard Python method:
var = 382
Most of the time using the standard Python number type is fine. Python will
automatically convert a number from one type to another if it needs. But,
under certain circumstances that a specific number type is needed (ie.
complex, hexidecimal), the format can be forced into a format by using
additional syntax in the table below:
Type Format Description
Most of the time Python will do variable conversion automatically. You can
also use Python conversion functions (int(), long(), float(), complex()) to
convert data from one
type
type to another. In function returns information about how your data
addition, the is stored
within a variable.
message = "Good
morning" num = 85
pi = 3.14159
String
Create string variables by enclosing characters in quotes. Python uses single
quote ' double " and triple """ to denote literal strings. Only the
s quotes quotes
"""
triple quoted also will automatically continue across the end of line
strings
statement.
firstName = 'john'
lastName = "smith"
message = """This is a string that will span across multiple lines. Using
newline characters
and no spaces for the next lines. The end of lines within this string also
count as a newline when printed"""
print var1[0] # this will print the first character in the string an `H`
print var2[1:5] # this will print the substring 'hinoP`
Python can use a special syntax to format multiple strings and numbers. The
string formatter is quickly covered here because it is seen often and it is
important to recognize the syntax.
The
{} are placeholders that are substituted by the and in
variables elemen count
t
the final string. This compact syntax is meant to keep the code more
readable and compact.
Python is currently transitioning to the format syntax above, but python
can use an older syntax, which is being phased out, but is still seen in
some example code:
List
Lists are a very useful variable type in Python. A list can contain a series of values. List
variables are declared by using brackets
[ ] following the variable name.
You can assign data to a specific element of the list using an index into the
list. The list index starts at zero. Data can be assigned to the elements of an
array as follows:
mylist = [0, 1, 2, 3]
mylist[0] = 'Rhino'
mylist[1] =
'Grasshopper'
mylist[2] = 'Flamingo'
mylist[3] = 'Bongo'
print mylist[1]
Lists aren’t limited to a single dimension. Although most people can’t
comprehend more than three or four dimensions. You can declare multiple
dimensions by separating an with commas. In the following example, the
MyTable variable is a two-dimensional array
:
Tuple
Tuples are a group of values like a list and are manipulated in similar ways.
But, tuples are fixed in size once they are assigned. In Python the fixed size
is considered immutable as compared to a list that is dynamic and mutable.
Tuples are defined by parenthesis ().
It seems tuples are very restrictive, so why are they useful? There are many
datastructures in Rhino that require a fixed set of values. For instance a
Rhino point is a list of 3 numbers [34.5, 45.7, 0] . If this is set as tuple,
then you can be assured the
original 3 number structure stays as a point (34.5, 45.7, 0) . There are
other datastructures such as lines, vectors, domains and other data in Rhino
that also require a certain set of values that do not change. Tuples are great
for this.
Dictionary
Dictionaries in Python are listsKey
of : Valu pairs. This is a very powerful datatype to
hold a lot of related information thate can be associated through keys . The main
operation of a dictionary is to extract a value based keyon the name.
Unlike lists, where index numbers are used, dictionaries allow the use
key
of a to access its
members. Dictionaries can also be used to sort, iterate and compare data.
Dictionaries are created by using braces ({}) with pairs separated by a comma
(,) and the key values associated with a colon(:). In Key must be unique.
Dictionaries the Here is a quick example on how
dictionaries might be used:
room_num = {'john': 425, 'tom': 212}
room_num['john'] = 645 # set the value associated with the 'john' key to 645
10
count = 0
count = count+1
print("Hello Geek")
Output:
Hello Geek
Hello Geek
11
Hello Geek
If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Try it Yourself »
In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we
know that 200 is greater than 33, and so we print to screen that "b is greater
than a".
12
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Try it Yourself »
Elif
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Try it Yourself »
Else
The else keyword catches anything which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are
equal") else:
print("a is greater than b")
Try it Yourself »
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print
to screen that "a is greater than b".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
14
With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
Python Functions
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
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
Output:: 10
var = 10 # declaring
globally def example():
var = 100 #declaring locally
print(var)
example() # calling the function
print(var)
Output
100
10
Syntax:
Example:
import random
for i in range(1,10):
val = random.randint(1,10)
print (val)
Output:: 3.14159
18
Opening Files in
Python
function to open a file. This function
open(
Python has a )
built-in returns a file
object, also called a handle, as it is used to read or modify the file
accordingly.
On the other hand, binary mode returns bytes and this is the mode
Mode Description
w Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
20
x Opens a file for exclusive creation. If the file already exists, the operation fails.
Opens a file for appending at the end of the file without truncating it. Creates a new file if it
a
doe exist.
Closing a file:
Close(): This is done to ensure that the file is free to use for
other resources
file.close()
image.resize(255,255)
Rotate(): Rotates the image to the specified degrees, counter
clockwise
image.rotate(90)
Mode: Gives the band of the image, ‘L’ for grey scale, ‘RGB’ for
true colour image
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
Raspberry pi is a low cost minicomputer 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. In addition to this , Raspberry Pi allows interfacing sensors, actuators ,
through th general purpose I/O pins(GPIO) .Since Raspberry Pi runs Linus Operating system, it
supports Python “out of the box”.
Specific Raspberry
model B
pi 3 Raspberry pi 2
model B
Raspberry Pi zero
ations
Key features
RAM 1GB SDRAM 1GB SDRAM 512 MB SDRAM
CPU Quad cortex Quad cortex ARM 11@ 1GHz
[email protected] A53@900MHz
GPU 400 MHz video core 250 MHz video core 250 MHz video core
IV IV IV
Ethernet 10/100 10/100 None
Wireless 802.11/Bluetooth None None
4.0
Video output HDMI/Composite HDMI/Composite HDMI/Composite
GPIO 40 40 40
1. System on Chip
The System on Chip (SoC) architecture that the Raspberry Pi 2 implements is the
Broadcom BCM2836, which we touched upon earlier in this chapter. This contains a
CPU, GPU, SDRAM, and single USB port. Each of these items is discussed in more
2. CPU
A central processing unit is the brain of your Raspberry Pi. It is responsible for
processing machine instructions, which are the result of your compiled programs.
3. GPU
The previous version of the Raspberry Pi Model B contained only a single microUSB
port and a two standard USB ports. The Raspberry Pi 2 has been expanded to
include an onboard 5 - port USB hub.
This allows you to connect four standard USB cables to the device and a single
microUSB cable. The micro USB port can be used to power your Raspberry Pi 2.
5. SD card Slot
Raspberry Pi does not have a builtin operating a system and storage. You can Plug-in SD card loaded
with a Linux image to the SD card slot.
8. Status LED’s :
Raspberry Pi has 5 status LED’s
33
9. Ethernet port
GPIO pins can accept both input and output commands and can be
controlled by programs in a variety of languages running on the Raspberry
Pi.
for example :The input could be readings from a temperature sensor, and
the output a command to another device to switch an LED on or off.
This port provides both video and audio output.You can connect the Raspberry Pi to a monitor
using HDMI cable .
Raspberry Pi comes with composite video output with RCA jack that
supports both PAL and NTSC video output. RCA jack can be used to
connect old televisions that have an RCA input only.
Raspberrypi has 3.5mm audio output jack .This audio jacks use for
providing audio output to old Televisions along with RCA jack for
video .The audio quality from this jack is inferior to the HDMI output
Connection :
Code
36
Code :
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
#switch Pin
GPIO.setup(25,GPIO.IN)
#LED Pin
GPIO.setup(18,GPIO.OUT)
state=False
37
def LED(pin):
state=not state
GPIO.output(pin,state)
while True:
try :
If(GPIO.input(25)==True):
LED(pin)
Sleep(1)
except KeyboardInterrupt:
exit()
Implementation of IoT
with Raspberry Pi
Internet Of Things is
Creating an interactive environment
Network of devices connected together
Sensor
Electronic element
Converts physical quantity into electrical signals
Can be analog or digital
DHT11 vs DHT22
We have two versions of the DHT sensor, they look a bit
similar and have the same pinout, but have different
characteristics. Here are the specs:
38
DHT11
Low cost
3 to 5V power and I/O requesting
2.5mA max current use during conversion (while
data)
Good for 0-100% humidity readings with 2-5% accuracy
Good for -40 to 80°C temperature readings ±0.5°C accuracy
No more than 0.5 Hz sampling rate (once every 2 seconds)
Body size 15.1mm x 25mm x 7.7mm
4 pins with 0.1" spacing
Actuator
Mechanical/Electro-mechanical device
Converts energy into motion
Mainly used to provide controlled motion to other
components
Relay
Relays are the switches which aim at closing and opening the circuits
electronically as well as electromechanically. It controls the opening and closing
of the circuit contacts of an electronic circuit.
40
System Overview
Sensor and actuator interfaced with Raspberry Pi
Read data from the sensor
Control the actuator according to the reading from thesensor
Connect the actuator to a device
Requirements
DHT Sensor (DHT22/AM2302)
4.7K ohm resistor
Relay
Jumper wires
Raspberry Pi
Mini fan
41
42
Connection: Relay(Switch )
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
43