0 ratings 0% found this document useful (0 votes) 27 views 45 pages Fiot Unit 3
Python is a versatile high-level programming language known for its multi-paradigm support, interpreted nature, and broad library support, making it suitable for cloud computing. It features various data types such as numbers, lists, tuples, strings, and dictionaries, and includes control structures like if...else statements and loops for decision making and iteration. Additionally, Python allows for module creation to organize code and reuse functionalities.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save FIOT UNIT 3 For Later Python
Python is a general-purpose high level programming language and suitable for providing a
solid foundation to the reader in the area of cloud computing.
‘The main characteristics of Python are
1) Multi-paradigm programminglanguage.
2) Python supports more than one programming paradigms including object- oriented
programming and structured programming.
3) InterpretedLanguage.
4) Python is an interpreted language and does not require an explicit compilationstep.
5) The Python interpreter executes the program source code directly, statement by
statement, as a processor or scripting engine does.
6 Interactive Language
7). Python provides an interactive mode in which the user can submit commands at the
Python prompt and interact with the interpreterdirectly.
get” iaetha Bytate pre ve fects He Cish ek postste cone ee Conse PON eeay
Beare lrcaeneare mtv ove onto = piers
+ Object and Procedure Oriented
° praia tebe waictan around procepires or Riketare test sho reuse oc
SREeE a cee ee ee eS
+ extendable
* Dear sone gmat Tee aS sae meer ren neuen hacen
+ Scalable
+ "Due tothe minimalistic nature of Python, it provides @ manageable structare for large programs
+ Port
rine yan an terete ngs prgranmers do nt have to worry about compton ting and ud ot
+ Broad Library Support
e hython hat abroad Hbrary support and works on various platforms such as Windows, Linu, Mac, ee
Python - Setup
* Windows
‘non binaries fr Windows can be downloaded from hn: aan yshon.or/aet
ha eramblor and ene the book, you would rive Pyro 2.7 hich eo be rect downloaded romDatatypes
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.
‘There are various data types in Python. Some of the important types are listed below.
Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category.
They are defined as int, float and complex class in Python. We can use the type() function to
know which class a variable or a value belongs to and the isinstance() function to check if an
object belongs to a particular class.
Scriptpy
la=
2. print(a, "is of type", type(a))
3.a-20
4, print(a, "is of type", type(a))
5.a=143j
6. print(a, "is complex mumber?", isinstance(1+2),complex))
Integers can be of any length, it is only limited by the memory available. A floating point
umber is accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. | is integer, 1.0 is floating point number. Complex numbers are written in the form, x +
yj, Where x is the real part and y is the imaginary part, Here are someexamples.
>> a= 1234567890123456789
>a
1234567890123456789
>>> b = 0.1234567890123456789
>>>b
0.12345678901234568>> = 143}
>>>e
aj)
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible, All the items in a list do not need to be of the same type. Declaring a list is pretty
straight forward. Items separated by commas are enclosed within brackets [J
1,2.2, ‘python’
We can use the slicing operator | | to extract an item or a range of items from a list. Index starts
form 0 in Python.
5,10,15,20,
15
3. print("al2|
4. # a[0:3]=[5, 10, 15]
5. print("a|0:3] =", 0:3)
6. #al5:] = [30, 35, 40]
7. print("al5:] =", al5:))
30,35,40]
",al2)
Lists are mutable, meaning: value of elements of a list can be altered.
>>> a=[1,23]
>>> al2|=4
>a
1.2.4)
Python Tuple
Tuple is an ordered sequences of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified. Tuples are used to write-protect data and
are usually faster than list as it cannot change dynamically. It is defined within parentheses ()
where items are separated bycommas.
‘program’, 1+3})
Script.pyt= (5,program’, 1+3))
#4{1)= program’
print("t{J=", a1)
# 10:3] = (9, ‘program’, (1+3)))
print("tL0:3] =", 1103)
# Generates error
# Tuples are immutable
110] =10
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings. Multi-line strings can be denoted using triple quotes, " or """
"This isa string!
multiline
Like list and tuple, slicing operator | | can be used with string. Strings are immutable
Script py
5,2,3,1,4}
# printing setvariable
"a)
# data type of variable a
print(type(a))
‘We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates. Since, set are unordered collection, indexing has no meaning. Hence the
slicing operator |J does not work. It is generally used when we have a huge amount of data
Dictionaries are optimized for retrieving data, We must know the key to retrieve the value. In
Python, dictionaries are defined within braces {} with each item being a pair in the
form key-value. Key and value can be of anytype
>>> d= {L:value'key'2}
>>> type(d)
We use key to retrieve the respective value. But not the other way around.
Script.pyI:value'key':2}
print(type(a))
print("dl1J = ".4l1));
print("dl/key'| =", d]'key'));
# Generates error
print("d|2| = "\d)2))
Python if...else Statement
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes. Decision making is
required when we want to execute a code only if a certain condition is satisfied.
The if...elif...else statement is used in Python for decision making.
Python if Statement
Syntax
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed. In Python, the body of
the if statement is indicated by the indentation. Body starts with an indentation and the first
unindented line marks the end. Python interprets non-zero values as True. None and 0 are
interpreted as False.
Python if Statement Flowchart,
Test. ~_ False
_ Expression _
True
,
Fig: Operation of statement
Example: Python if Statement
# If the number is positive, we print an appropriate message
num =3
ifnum> 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num>0:
print(num, "is a positive number.")
print("This is also always printed. ")
‘When you run the program, the output willbe
3 is a positivenumber
This is alwaysprinted
This is also always printed
In the above example, num > 0 is the test expression. The body of if is executed only if this
evaluates to True.
‘When variable num is equal to 3, test expression is true and body inside body of if is executed. If
variable num is equal to -1, test expression is false and body inside body of if is skipped
The print() statement falls outside of the if block (unindented). Hence, it is executed regardless
of the testexpression.
Python if...else Statement
Syntax
if test expression:
Body of ifelse:
Body of else
‘The if else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
Python if.else Flowchart
\
Test False
__ Expression
rue
i
Body of if Body of else
Fg: Operation of .ate statement
Example of if..clse
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num =-5
#num =0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
In the above example, when num is equal to 3, the test expression is true and body of
executed and body of else is skipped.
If num is equal to -5, the test expression is false and body of else is executed and body of if is
skipped.
If num is equal to 0, the test expression is true and body of if'is executed and body of else is
skipped.Python if..elif..clse Statement
Syntax
if test expression:
Body of if
elif test expression:
Body of elif
else
Body of else
The elif is short for else if. It allows us to check for multiple expressions. If the condition
for if is False, it checks the condition of the next elif block and so on. If all the conditions
are False, body of else is executed. Only one block among the several if..elif...else blocks is
executed according to the condition. The if block can have only one else block. But it can have
multiple elifblocks.
Flowchart of if...clif...lse
Test False
\
sa
Test False
Expression
[raven rein
[True
t +
Body of elif Body of else
j—__ ke
'
Fig: Operation of i.
Example of if...elif...else
# In this program,
# we check if the mumber is positive ot
# negative or zero and
# display an appropriate message
um =3.4# Try these two variations as well:
# nm =0
# num =-4.5
ifnum> 0
print("Positive number")
elif num = 0:
print("Zero")
else
print("Negative number")
‘When variable num is positive, Positive number is printed,
If num is equal to 0, Zero is printed
If num is negative, Negative number is printed
Python Nested if statements
‘We can have a if.elif..else statement inside another if.elif..else statement. This is called
nesting in computer programming. Any number of these statements can be nested inside one
another. Indentation is the only way to figure out the level of nesting. This can get confusing, so
must be avoided if we ean.
Python Nested if Example
# Inthis program, we input a number
# check if the number is positive or
# negative or zero anddisplay
# an appropriate message
# This time we use nested if
‘num = float(input("Enter a number: "))
if num >= 0:
ifnum = 0:
print("Zero")
else:
print("Positive number")
else
print("Negative number")
Output 1
Enter a mumber: 5
Positive number
Output 2
Enter a number: -1Negative number
Output 3
Enter a number: 0
Zero
Python for Loop
‘The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Flowchart of for Loop
Syntax
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4,2, 5,4, 11]
# variable to store the sum
sum =0
# iterate over the list
for val in numbers:
stun = sum+val
# Output: The sum is 48
print("The sum is", sum)
when you run the program, the output will be
The sum is 48
‘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 funetion does not store all the values in emory,
it would be inefficient. So it remembers the start, stop, step size and generates the next number
on thego.
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)))
10# Output: |2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
# Output: [2, 5,8, 11, 14, 17)
print(list(range(2, 20, 3)))
‘We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing. Here is an
example,
# Program to iterate through a list using indexing
genre = ['pop’, ‘rock’, 'jazz']
# iterate over the list using index
fori in range(len(genre))
print("I like", genre|i))
‘When yourun the program, the output will be:
1 likepop
liketock
Tikejazz
What is while loop in Python?
‘The while loop in Python is used to iterate over a block of code as long as the test expression (condition)
istrue, We generally use this loop when we don't know beforehand, the number of times to iterate.
Syntax of while Loop in Python
while test_expression
Body of while
In while loop, test expression is checked first, The body of the loop is entered only if the test_expression
evaluates to Thue, After one iteration, the test expression is checked again. This process continues until
the test_expression evaluates to False. In Python, the body of the while loop is determined through
indentation. Body staits with indentation and the first unindented line marks the end, Python interprets
any non-zero value a5 True. None and 0 are interpreted asFalse.
Flowchart of while Loop
# Program to add natural
# numbers upto
# sum = 14243+..4n
# To take input from the user,
#n = int(input("Enter n: "))
0
# initialize sum and counter
sum =0
i=1
while i
sum = sum +i
11i-it1 — # updatecounter
# print thesum
print("The sum is", sum)
‘When you run the program, the output will be:
Enter n: 10
‘The sum is 55
In the above program, the test expression will be True as long as our counter variable i is less than or
equal to n (10 in ourprogram),
We need to increase the value of counter variable in the body of the loop. This is very important (and
‘mostly forgotten). Failing to do so will result in an infinite loop (never ending loop).
Finally the result is displayed.
Python Modules
A file containing a set of functions you want to include in the application is called Module.
Create a Module
To create a module just save the code you want in a file with the file extension py:
Example
Save this code in a file named mymodule py
def greeting(name):
print("Hello, " + name)
Usea Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Fonathan")
Note: When using a fimetion from a module, use the syntax: module_name.funetion_name.
Variables in Module
‘The module can contain functions, as already described, but also variables of all types(artays,
dictionaries, objects etc):
Example
Save this code in the file mymodule.py
12person] "John","age": 36,"country": "Norway"}
Example
Import the module named mymodule, and access the person! dictionary:
import mymodule
a= mymodule.person!|"age"|
print(a)
Naming a Module
‘You can name the module file whatever you like, but it must have the file extension py
Re-naming a Module
‘You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a=mx.person]|"age"|
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
Import and use the platform module:
import platform
x= platform. system(,
print(x)
Using the dir) Function
‘There is a built-in function to list all the function names (or variable names) in a module, The
dix() function:
Example
List all the defined names belonging to the platform module:
import platform
13x= dir(platform)
prints)
Note: The dir() function can be used on all modules, also the ones you create yourself.
Import from Module
‘You can choose to import only parts from a module, by using the from keyword.
Example
‘The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person! = {"name": "John", "age": 36, "countr
': "Norway"}
Example
Import only the person! dictionary from the module’
from mymodule import person
print (personl["age"|)
Note: When importing using the from keyword, do not use the module name when referring to
elements in the module. Example: person]|"age" |, not mymodule. person] "age" |
Packages
‘We don't usually store all of our files in our computer in the same location. We use a well-
organized hierarchy of directories for easier access. Similar files are kept in the same directory,
for example, we may keep all the songs in the "music" directory. Analogous to this, Python has
packages for directories and modules for files. As our application program grows larger m size
with a lot of modules, we place similar modules in one package and different modules in
different packages. This makes a project (program) easy to manage and conceptuallyclear.
Similar, as a directory can contain sub-directories and files, a Python package can have sub-
packages and modules. A directory must contain a file namedinit py in order for Python to
consider it as a package. This file can be left empty but we generally place the initialization code
for that package in this file. Here is an example. Suppose we are developing a game, one possible
organization of packages and modules could be as shown in the figure below.
Package Module Structure in Python Programming
Importing module from a package
‘We can import modules from packages using the dot (.) operator. For example, if want to import
the start module in the above example, it is done as followsimport Game Level start
Now if this module contains a function named select_difficulty(), we must use the full name to
reference it,
Game .Level start select_difficulty(2)
If this construct seems lengthy, we ean import the module without the package prefix as follows.
from Game.Level import start
‘We can now call the function simply as follows.
start seleet_difficulty(2)
Yet another way of importing just the required funetion (or class or variable) form a module
within a package would be as follows.
from Game Level.start import select difficulty
Now we can directly call this fimetion.
select_ditticulty(2)
Although easier, this method is not recommended. Using the full namespace avoids confusion
and prevents two same identifier names from colliding. While importing packages, Python looks
in the hst of directories defined in sys.path, similar as for module search path.
Files
File is a named location on disk to store related information. It is used to permanently store data
in a non-volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile
which loses its data when computer is turned off, we use files for future use of the data. When
‘we want to read from or write to a file we need to open it first. When we are done, it needs to be
closed, so that resources that are tied with the file are freed. Hence, in Python, a file operation
takes place in the followingorder
1. Openafile
2. Read or write (perform operation)
3. Close thefile
How to open a file?
Python has a built-in function open) to open a file. This function returns a file object, also called
ahandle, as it is used to read or modify the file accordingly.
15>>> feopen("testtxt") _# open file in currentdirectory
>>> f= open("C:/Python33/README .txt") # specifying full path
‘We can specify the mode while opening a file, In mode, we specify whether we want to read 'r',
vite 'w or append 'a' to the file. We also specify if we want to open the file in text mode or
binary mode. The default is reading in text mode. In this mode, we get strings when reading from
the file. On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files
Python File Modes
‘Mode | Description
1 _| Opena file for reading. (default)
‘w' | Open file for writing. Creates a new file if it does not exist or truncates the file if it
exists,
(Open a file for exclusive creation, Ifthe file already exists, the operation fails.
Open for appending at the end of the file without truncating it. Creates a new file ifit
does not exist
‘| Open in text mode. (default)
Open in Binary mode.
“| Open a file for updating (reading and writing)
fopen("testtxt") 4 equivalent to or‘
f= open("test.txt",'w’) # write in textmode
open"img.bmp",r+b’) # read and write in binary mode
Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using
ASCII (or other equivalent encodings). Moreover, the default encoding is platform dependent. In
windows, it is 'cp1252" but 'utf-8' in Linux. So, we must not also rely on the default encoding or
else our code will behave differently in different platforms. Hence, when working with files in
text mode, it is highly recommended to specify the encoding type.
= open(“test.txt",mode = 'r'encoding = 'utf-8')
How to close a file Using Python?
‘When we are done with operations to the file, we need to properly close the file. Closing a file
will free up the resources that were tied with the file and is done using Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file
f= open("test.txt" encoding = 'utt-8')
16# perform file operations
fecloseQ)
This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try:
£= open("test.txt",encodin,
# perform file operations
finally:
feloseQ,
WES)
This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop. The best way to do this is using the with statement. This ensures
that the file is closed when the block inside with is exited. We don't need to explicitly call the
close() method. It is doneinternally.
with open("test.txt" encoding = ‘utf-8') as f
# perform file operations
How to write to File Using Python?
In order to write into a file in Python, we need to open it in write ‘w,, append 'a' or exclusive
creation ‘x’ mode. We need to be careful with the 'w’ mode as it will overwrite into the file if it
already exists. All previous data are erased, Writing a string or sequence of bytes (for binary
files) is done using write) method. This method retums the number of characters written to the
file
with open("test.txt",'w'encoding = utf-8') as f:
Evwrite("my first file\n")
£write("This file\w\n")
f.write("contains three lines\n")
‘This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten. We must include the newline characters ourselves to distinguish different lines.
How to read files in Python?
To read a file in Python, we must open the file in reading mode. There are various methods
available for this purpose. We can use the read(size) method to read in size number of data. If
size parameter is not specified, it reads and returns up to the end of the file
>>> f= open("test.txt"/1’encoding = 'utf-8')
>>> firead(4) # read the first 4 data
17"This!
>>>fread(4) — # read the next 4 data
is’
>>>fread() _# read in the rest tll end of file
‘my first file\nThis file\ncontains threelines\n"
> fread() # further reading retums empty sting
We can see that, the read() method retums newline as "\n'. Once the end of file is reached, we get
empty string on further reading. We can change our current file cwsor (position) using the seek)
‘method, Similarly, the tell) method returns our current position (in number of bytes)
>>ofitell — # get the current file position
56
>>> f'seek(0) # bring file cursor to initial position
0
>>> print(fread() # read the entire file
This is my first file
This file
contains three lines
‘We can read a file line-by-line using a for loop. This is both efficient and fast
>>> for line in f:
priniine, en
This is my first file
This file
contains three lines
The lines in file itself has a newline character ‘wn’
Moreover, the print() end parameter to avoid two newlines when printing. Altemately, we can
use readline() method to read individual lines of a file. This method reads a file till the newline,
including the newlinecharacter.
>>> fireadlineQ)
"This is my first file\n’
>>> freadline()
"This file\n!
18>>> freadline()
‘contains three lines\n’
>>> freadline()
Lastly, the readlines() method retums a list of remaining lines of the entire file, All these reading
method return empty values when end of file (EOF) is reached.
>>> freadlines()
[This is my first file\n, "This filein, ‘contains three lines'n'|
Python File Methods
There are various methods available with the file object. Some of them have been used in above
examples. Here is the complete list of methods in text mode with a brief description,
Python File Methods
Method Description
elose0 lose an open fle. Ithas no effect ithe file is already closed.
detach) ‘Separate the underlying binary buffer from the TextlOBase and return i
‘leno ‘Retumn an integer number (fle descriptor) of the file
AushO) Flush the waite buffer of the fie stream,
isatty) ‘Retum True ifthe file stream is interactive.
read(a) Read at most n characters form the file. Reads till end of file iit is negative or None.
readable Retums True ifthe file stream can be read from.
realine(—1) ‘Read and refurn one line from the file. Reads in af most n bytes if specified.
readlines(a—1) ‘Read and return a lst of lines from the file. Reads in at most n bytescharacters if specified
seek(oflset.fiom-SE | Change the file position to offset bytes, in reference to from (start, current, end).
EK_SET)
seckableO) ‘Returns True ifthe file stream supports random access
tell ‘Returns the current file location.
‘truncate(size-None) Resize the file stream to size bytes. If size is not specified, resize to current location.
writable Returns True ifthe file stream can be written to.
writes) ‘Write string sto the file and return the number of characters written.
‘writelines(lines) Write a list of lines to the file
Method Description
close() Close an open file. It has no effect if the file is already closed.
detach) Separate the underlying binary buffer from the TextIOBase and returnit.
filenoQQRetum an integer number (file descriptor) of thefile.
flushQ Flush the write buffer of the file stream.
isatty() Retum True if the file stream is interactive
read(n) Read at most n characters form the file. Reads till end of file if itis negative or None
19readable) Returns True if the file stream can be readffom.
readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Read and return a list of lines from the file. Reads in at most n
bytes/characters ifspecified
seek(offset,fiom-SEEK SET) Change the file position to offset bytes, in reference to from
(start, current,end).
seekableQ) Returns True if the file stream supports randomaccess.
tell) Retums the current filelocation.
truncate(size-None) Resize the file stream to size bytes. If size is not specified, resize to
currentlocation,
writable Returns True if the file stream can be writtento
write(s) Write string s to the file and return the number of characterswritten.
writelines(lines) Write a list of lines to thefile.
UNIT IV
IoT PHYSICAL DEVICES AND ENDPOINTS
ToT Device
A "Thing" in Intemet of Things (IoT) can be any object that has a unique identifier and which
can send/receive data (including user data) over a network (eg, smart phone, smartTV,
computer, refrigerator, car, etc.)
+ IoT devices are connected to the Intemet and send information about themselves or about their
surroundings (¢.g. information sensed by the connected sensors) over a network (to other devices
or servers/storage) or allow actuation upon the physical entities/environment around them
remotely.
IoT Device Examples
A home automation device that allows remotely monitoring the status of appliances and
controlling the appliances. + An industrial machine which sends information abouts its operation
and health monitoring data to a server. + A car which sends information about its location to a
20Introduction toRaspberry Pi
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 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 VO pins. Since Raspberry Pi runs Linux operating system, it
supports Python "out of the box".
Raspberry Pi
Linux on Raspberry Pi
1. Raspbian: Raspbian Linux is a Debian Wheezy port optimized for RaspberryPi.
2. Arch: Arch is an Arch Linux port for AMDdevices.
3. Pidora: Pidora Linux is a Fedora Linux optimized for RaspberryPi.
4. RaspBMC: RaspBMC is an XBMC media-center distribution for RaspberryPi. 945. OpenELEC: OpenELEC is a fast and user-friendly XBMC media-centerdistribution.
6. RISC OS: RISC OS is a very fast and compact operatingsystem.
Raspberry Pi GPIO
mg |»
erornen 10 ©] w
worn |Q | wave
001 /Q O| romney,
cw |Q O| erosrncy
011 |Q Q| eo»
@orinowe |Q Q| von
@onoxn |@ Q| vorroan
oan |Q | corer
Raspherry Pi Interfaces
. Serial: The serial interface on Raspberry Pi has receive (Rx) and transmit
(Tx) pins for communication with serialperipherals.
. SPI: Serial Peripheral Interface (SPI) is a synchronous serial data protocol
used for communicating with one or more peripheraldevices.
. 12C: The I2C interface pins on Raspberry Pi allow you to connect hardware
modules. 12C interface allows synchronous data transfer with just two pins -
SDA (data line) and SCL (clockline).
22Raspberry Pi Eample: Interfacing LED and switch with Raspberry Pi
from time import sleeP
import RPi.GPIO
asGPIO
GPIO.setmode(GPIO.B
cM)
#Switch Pin
GPIO.setup(25,GPIO.IN)
#LEDPin
GPIO.setup(18,GPIO.OUT)
state=false
deftoggleLED(pin):
23state = not state
GPIO.output(pin,st
ate)
whileTrue:
toggleLED(p
in) sleep(.01)
24exceptKeyboardInterrupt:
exit()
Raspberry Pi Camera interfacing:
Learn how to connect the Raspberry Pi Camera Module to your Raspberry Pi and take
pictures, record video, and apply image effects.
Connect the Camera Module
Ensure your Raspberry Pi is turned off.
1. Locate the Camera Module port
2. Gently pull up on the edges of the port’s plastic clip
3. Insert the Camera Module ribbon cable; make sure the cable is the right way round
4, Push the plastic clip back into place
25How to control the Camera Module via the command line
Now your Camera Module is connected and the software is enabled, try out the
Fraspistillemaraspividl
© Open a terminal window by clicking the black monitor icon in the taskbar:
command line tool:
© Type in the following command to take a still picture and save it to the Desktop:
Sane mens
o Press Enter to run the command.
When the command runs, you can see the camera preview open for five seconds before
a still picture is taken.
co Look for the picture file icon on the Desktop, and double-click the file icon to open
the picture.
6 OCE*6
26By adding different options, you can set the size and look of the image
the command takes.
© For example,
and — to change the height and width of the image:
2 Now record a video with the Camera Module by using the
following command:
o In order to play the video file, double-click the file icon on the Desktop
to open it in VLC Media Player.
How to control the Camera Module with Python code
The Python library allows you to control your Camera Module and create
amazing projects.
© Opena Python 3 editor, such as Thonny Python IDE:
27any Programmer's Editor
vo Sound & Video >
™
vv Graphics *
# Shutdown. 8 Wolfram
Open anew file and save it as
rts!
Note: it’s important that you never save the file as AEN O
o Enter the following code
Paani org oes
Troan ea ea a)
camera = PiCamer
28CRE Coat ZO)
sleep(5)
camera.stop_preview()
Save and run your program. The camera preview should be shown for five seconds
and then close again
Note: the camera preview only works when a monitor is connected to your
Raspberry Pi. If you are using remote access (such as SSH or VNC), you won't’ see
the camera preview
o If your preview is upside-down, you can rotate it by 180 degrees with the following
code:
© camera = PiCamera()
Cone mcrett tery
Pat degrees. To reset the image.
You can rotate the image by
set Rien to J degrees.
It’s best to make the preview slightly see-through so you can see whether errors occur
in your program while the preview is on.
> Make the camera preview see-through by setting an level
Build value can be any number bet
Take still pictures with Python code
Now use the Camera Module and Python to take some still pictures.
29> Amend your code to add a SURCEeaM) line:
Eon
sleep(5)
Uae Reni
Conform mares)
Note: it’s important to $E3q for at least two seconds before capturing an image,
because this gives the camera’s sensor time to sense the light levels.
Run the code.
You should see the camera preview open for five seconds, and then a still picture
should be captured. As the picture is being taken, you can see the preview briefly adjust
toa different resolution.
Your new image should be saved to the Desktop.
2 Now add a loop to take five pictures in a row:
camera.start_preview()
oeeny
sleep(5)
Cetitor Meta tta(
1.stop_preview()
‘The variable ff counts how many times the loop has run, from J to |. Therefore, the
images get saved as ERRCOM eS, Meee
o Run the code again and hold the Camera Module in position
and so on.
‘The camera should take one picture every five seconds. Once the fifth picture is taken,
the preview closes.
> Look at your Desktop to find the five new pictures
30Recording video with Python code
Now record a video!
o Amend your code to remove and instead
Bgstart_recording()Eumgstop_recording()}
Your code should look like this now:
Sion esac
Cerner Met seoc TT
ep(S)
Jcamera.stop_recording()
Cerner Race Mesa io)
Run the code.
Your Raspberry Pi should open a preview, record 5 seconds of video, and then close the
preview.
Implementation of IoT with raspberry pi
Temperature Dependent Auto Cooling System
System Overview
* Snesor 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
31= 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)
Pin] -SV Power or 3.3 v Power
Pin2-Data
Pin3-Null
Pin4-Grornd
vVvvv
Relay
* Mechanical/electromechanical switch
= 3 output terminals (left to right)
* NO (normal open):
= Common
= NC (nommal 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...
* Goto folder Adafruit_Python_DHT
ed 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)
33GPIO.setwarnings(False)
sensor = Adafruit_DHT.AM2302
print (‘Getting data from the sensor’
humidity, temperature = Adafruit_DHT.read_retry(sensor,17)
print (‘Temp=(0:0.1f}*C humidity={ 1:0.1f}%'.format(temperature, humidity)
Code:
File: 10TSR.py
34Output
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:
GP10.output(13,0) # Relay is active low print(*Relay is on’)
35sleep(5)
GPIO.output(13,1) # Relay is turned off after delay of 5 seconds
36Connection: 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
* Rum the existing code. The fan should operate when the surrounding temperature
is greater than the threshold value in the sketch
Result
The fan is switched on whenever the temperature is above the threshold value set in
the code.
Notice the relay indicator turned on.
37Implementation of oT with Raspberry Pi-II
IOT: Remote Data Logging
= Collect data from the devices in the network
= Send the data to a server/remote machine
* Control the network remotely
System Overview:
* A network of Temperature and humidity sensor connected with Raspberry Pi
* Read data from the sensor
* Send it to a Server
38* Save the data in the server
Requirements
* DHT Sensor
* 4.7K ohm resistor
* Jumper wires
* Raspberry Pi
DHT Sensor
Digital Humidity and ‘Temperature Sensor (DHT)
+ PIN 1, 2. 3,4 (from left to right)
» Pinl -5V Power or 3.3 v Power
Pin2-Data
W
Vv
Pin3-Null
Pin4-Grornd
v
Sensor- Raspberry Pi Interface
* 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
Read Data from the Sensor
Adafruit provides a library to work with the DHT22 sensor
Install the library in Raspberry Pi
39Use the func
ion Adafri
it_DHT.read_retry() to read data from the sensor
GWU nano 2.2.
TOTSRpy
LOLTOR. Py
Sending Data to a Server
Sending data to §
erver using network protocols
40= Create a server and client
* Establish connection between the server and the client
* Send data from the client to the server
Socket Programming:
* Creates a two-way communication between two nodes in a network
= The nodes are termed as Server and Client
= Server performs the task/service requested by the client
Creating a socket:
socket.socket (SocketFamily, SocketType, Protocol=0)
¥ SocketFamily can be AF_UNIX or AF_INET
Y SocketType can be SOCK_STREAM or SOCK_DGRAM.
¥ Protocol is set default to 0
Server:
ocket.socket() # creating a socket object
Host=socket.gethostname() # local machine
port = 12321 # port number for the server
s.bind((host, port) # bind to the port number to the srever
s.listen(5) # waiting for the client to connect
while True: # accept the connection request from the client
41print ‘Connected to’, addr c,addr = s,accept()
c.send(*Connection Successfitl’)
c.close()
Client:
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close()
Client Code: Obtain readings from the sensor
def sensordata():
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
sensor = Adafruit_DHT.AM2302
humidity, temperature = Adafruit_DHT-read_retry(sensor,17) return(humidity,
temperature)
42This function returns the values from the DHT sensor
Client Code: Connecting to the server and sending the data
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address =
(110.14.3.194', 10001)
try:
while (1):
h,t=sensordata() message = str(h)+'+str(t) #Send data
print >>sys.stderr, ‘sending "%s"" % message
sent = sock.sendto(message, server_address)
finally:
print >>sys.stderr, ‘closing socket’ sock.close()
Server Code: Receive data from client and save it
sock = socket.socket(socket.AF_INET, socket. SOCK_DGRAM)
# Bind the socket to the port
server_address = ('10.14.3.194', 10001)
sock.bind(server_address)
while True:
data, address = sock.reevfrom(4096) with open(“Datalog.txt","a") as f
43mess=str(data) f.write(mess) print mess
m_ the sensor and sends it to the server
. The server receives the data from the client and saves it in a text file
DataLog.txt
LT)
eee
Eee}
-9000015259, 23.
Dey eee
REL eae)
9000015259, 23.
Oe
Tee
9000015259, 23
Ce
eee
eee
4445