0 ratings 0% found this document useful (0 votes) 17 views 35 pages U3 Fiot
Fundamental internet of things
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
Go to previous items Go to next items
Unit -3
Introduction to Python programming:
What is Python?
Python is a high-level scripting language which can be used for a wide
varietyof text processing, system administration and internet-related
tasks. Unlikemany similar languages, it’s core language is very small and
easy to master, while allowing the addition of modules to perform a
virtually limitlessvariety of tasks. Python is a true object-oriented
language, and is availableon a wide variety of platforms. There's even a
python interpreter writtenentirely in Java, further enhancing python's
position as an excellent solutionfor internet-based problems.Python was
developed in the early 1990's by Guido van Rossum, thenat CWI in
Amsterdam, and currently at CNRI in Virginia. In some ways,python grew
out of a project to design a computer language which would beeasy for
beginners to learn, yet would be powerful enough for even
advancedusers. This heritage is reflected in python’s small, clean syntax
and the thoroughness of the implementation of ideas like object-
orientedprogramming,without eliminating the ability to program in a more
traditional style. Sopython is an excellent choice as a first programming
language without sacrificing the power and advanced capabilities that
users will eventually need
The very Basics of Python
There are a few features of python which are different than other
programming languages, and which should be mentioned early on so that
subsequentexamples don’t seem confusing. Python statements do not
need to end with a special character - thepython interpreter knows that
you are done with an individual statementby the presence of a newline,
which will be generated when you press the”Return” key of your
keyboard. If a statement spans more than one line, thesafest course of
action is to use a backslash (\) at the end of the line to letpython know
that you are going to continue the statement on the next line;you can
continue using backslashes on additional continuation lines, Python
provides you with a certain level of freedom when composing aprogram,
but there are some rules which must always be obeyed. One ofthese
rules, which some people find very surprising, is that python uses
indentation (that is, the amount of white space before the statement
itself) toindicate the presence of loops, instead of using delimiters like
curly braces({}) or keywords (like “begin” and “end”) as in many otherlanguages. Theamount of indentation you use is not important, but it must
be consistentwithin a given depth of a loop, and statements which are not
indented mustbegin in the first column.
Python Features:
1. Easy-to-learn — Python has few keywords, simple structure, and a
clearly defined syntax. This allows a student to pick up the language
quickly.
2. Easy-to-read — Python code is more clearly defined and visible to the
eyes.
3. Easy-to-maintain — Python's source code is fairly easy-to-maintain.
4. A broad standard library — Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and Macintosh.
5. Interactive Mode — Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
6.Portable — Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
7. Extendable — You can add low-level modules to the Python
interpreter, These modules enable programmers to add to or customize
their tools to be more efficient.
8. Databases - Python provides interfaces to all major commercial
databases.
9. GUI Programming — Python supports GU! applications that can be
created and ported to many system calls, libraries and windows systems,
such as Windows MFC, Macintosh, and the X Window system of Unix.
10. Scalable — Python provides a better structure and support for large
programs than shell scripting
Basic Principles of Python
Python has many features that usually are found only in languages
whichare much more complex to learn and use, These features were
designed intopython from its very first beginnings, rather than being
accumulated intoan end result, as is the case with many other scripting
languages. If you’renew to programming, even the basic descriptions
which follow may seemintimidating. But don’t worry - all of these ideas
will be made clearer inthe chapters which follow. The idea of presenting
these concepts now is tomake you aware of how python works, and the
general philosophy behindpython programming. If some of the conceptsthat are introduced here seemabstract or overly complex, just try to get a
general feel for the idea, and thedetails will be fleshed out later
1) Basic Core Language
Python is designed so that there really isn’t that much to learn in the
basiclanguage. For example, there is only one basic structure for
conditional programming (if/else/elif), two looping commands (while and
for), and aconsistent method of handling errors (try/except) which apply
to all pythonprograms. This doesn’t mean that the language is not flexible
and powerful, however. It simply means that you’re not confronted with an
overwhelmingchoice of options at every turn, which can make
programming a much simplertask.
2) Modules
Python relies on modules, that is, self-contained programs which define
avariety of functions and data types, that you can call in order to do tasks
beyond the scope of the basic core language by using the import
command, Forexample, the core distribution of python contains modules
for processing files,accessing your computer's operating system and the
internet, writing CGl(Common Gateway Interface)scripts which handle
communicating with pages displayed in web browsers,string handling and
many other tasks.
3) Object Oriented Programming
Python is a true object-oriented language. The term “object oriented”
hasbecome quite a popular buzzword; such high profile languages as C++
andjava are both object oriented by design. Many other languages add
someobject-oriented capabilities, but were not designed to be object
oriented fromthe ground up as python was, Why is this feature important?
Object oriented program allows you to focus on the data you're interested
in, whetherit's employee information, the results of a scientific experiment
or survey,setlists for your favorite band, the contents of your CD
collection, information entered by an internet user into a search form or
shopping cart, andto develop methods to deal efficiently with your data. A
basic concept ofobject oriented programming is encapsulation, the ability
to define an objectthat contains your data and all the information a
program needs to operateon that data. In this way, when you call a
function (known as a method inobject-oriented lingo), you don’t need to
specify a lot of details about yourdata, because your data object “knows”
all about itself. In addition, objectscan inherit from other objects, so if you
or someone else has designed an object that's very close to one you're
interested in, you only have to constructthose methods which differ from
the existing object, allowing you to save alot of work.Another nice feature
of object oriented programs is operator overloading.What this means is
that the same operator can have different meaningswhen used with
different types of data. For example, in python, when you'redealing withnumbers, the plus sign (+) has its usual obvious meaning ofaddition. But
when you're dealing with strings, the plus sign means to jointhe two
strings together. In addition to being able to use overloading forbuilt-in
types (like numbers and strings), python also allows you to definewhat
operators mean for the data types you create yourself.
Python uses the object model abstraction for data storage. Any construct
that contains
any type of value is an object. Although Python is classified as an "object-
orientedprogramming (OOP) language," OOP is not required to create
perfectly working Python applications. You can certainly write a useful
Python script without the use of classes and instances. However, Python's
object syntax and architecture encourage or "provoke" this type of
behavior. Let us now take a closer look at what a Python object is.
All Python objects have the following three characteristics: an identity, a
type, and a value.
IDENTITY--Unique identifier that differentiates an object from all others.
Any object's identifier can be obtained using the id() built-in function (BIF).
This value is as close as you will get to a "memory address" in Python
(probably much to the relief of some of you). Even better is that you
rarely, if ever, access this value, much less care what it is at all.
TYPE--An object's type indicates what kind of values an object can hold,
what operations can be applied to such objects, and what behavioral rules
these objects are subject to. You can use the type() BIF to reveal the type
of a Python object. Since types are also objects in Python (did we mention
that Python was object-oriented?), type() actually returns an object to you
rather than a simple literal.
VALUE--Data item that is represented by an object.
4) Exception Handling
Regardless how carefully you write your programs, when you start
usingthem in a variety of situations, errors are bound to occur. Python
providesa consistent method of handling errors, a topic often referred to
as exceptionhandling. When you're performing an operation that might
result in anerror, you can surround it with a try loop, and provide an
except clause totell python what to do when a particular error arises.
While this is a fairlyadvanced concept, usually found in more complex
languages, you can startusing it in even your earliest python programs.
As a simple example, consider dividing two numbers. If the divisor iszero,
most programs (python included) will stop running, leaving the userback
at a system shell prompt, or with nothing at all. Here’s a little
pythonprogram that illustrates this concept; assume we've saved it to a
file calleddiv.py:
#1Jusr/local/bin/python
x=7
y=0
print x/y
print "Now we're done!"
When we run this program, we don’t get to the line which prints the
message,
because the division by zero is a “fatal” error:
% div.py
Traceback (innermost last):
File “div.py", line 5, in?
print x/y
ZeroDivisionError: integer division or modulo
While the message may look a little complicated, the main point to
noticeis that the last line of the message tells us the name of the
exception thatoccured. This allows us to construct an except clause to
handle the problem:
x=7
y=0
try:
print x/y
except ZeroDivisionError:
print "Oops - | can’t divide by zero, sorry!"
print "Now we're done!"
Now when we run the program, it behaves a little more nicely:
% div.py
Oops - | can’t divide by zero, sorry!
Now we're done!
Since each exception in python has a name, it’s very easy to modify
yourprogram to handle errors whenever they're discovered. And of
course, if youcan think ahead, you can construct try/except clauses to
catch errors beforethey happen.Data typesin python
Standard Types
+ Numbers (separate subtypes; three are integer types)
o Integer
= Boolean
= Long integer
© Floating point real number
© Complex number
* String
+ List
+ Tuple
* Dictionary
* Types of Numeric Data
Python supports four types of numeric objects: integers, long integers,
floating point numbers, and complex numbers. In general, python will not
automatically convert numbers from one type to another, although it
providesa complete set of functions to allow you to explicitly do these
conversions.
To enter numeric data inside an interactive python session or in a
script,simply set the value of a variable to the desired number. To specify
a floatingpoint number, either include a decimal point somewhere in the
number, or useexponential notation, for example 1e3 or 1£3 to represent
1000 (1 times 10to the third power). Note that when using exponential
notation, numbersare always stored as floating point, even if there is no
decimal point.Long integers can be entered by following an ordinary
integer with theletter “L", either lowercase (e.g. 27!) or uppercase (e.g.
271). (Since alowercase “I” looks so much like the number “1”, you may
want to get in thehabit of using uppercase “L"s in this context.) In python,
long integers areactually what are sometimes called “arbitrary precision”
integers, since theycan have as many digits as you have the patience to
type into the computer.On most computers, ordinary integers have a
range from about -2 billionto +2 billion. Trying to use an integer larger
than this value results in anOverflowError.
>>> x = 2000000000
>>> K=x+x/2
Traceback (innermost last):File "", line 1, in ?
OverflowError: integer addition
You'll never see such an error when using a long integer:
>>> x = 2000000000L
>>> xKax+x/2
>>>x
3000000000L
Working with numbers in python
#integer
>>>a=5
>>>type(a)
#floating point
>>>b=2.5
>>>type(b)
#Long
>>>x=988848989897L
>>>type(x)
#complex
>>>y=245)
>>>y
(2+5))
>>>typely)
>>>y.real2
>>>y.imag
5
#addition
>>>c=atb
>>>c
75
>>>type(b)
#subtraction
>>>d=a-b
>>od
175
>>>type(d)
* String Constants
Strings are a collection of characters which are stored together to
representarbitrary text inside a python program. You can create a string
constantinside a python program by surrounding text with either single
quotes ("),double quotes ("), or a collection of three of either types of
quotes (""" or"). In the first two cases, the opening and closing quotes
must appear onthe same line in your program; when you use triple
quotes, your text canspan as many lines as you like. The choice of which
quote symbol to use isup to you - both single and double quotes have the
same meaning in python.Here are a few examples of how to create a
string constant and assign itsvalue to a variable:
name = ‘Phil’
value = "$7.00"
helptext = """You can create long strings of text
spanning several lines by using triple quotes at
the beginning and end of the text"When the variable helptext is printed it would display as three lines, with
the line breaks at the samepoints as in the triple-quoted text.Using a
single backslash as a continuation character is an alternativeto using
triple quoted strings when you are constructing a string constant.Thus,
the following two expressions are equivalent, but — most
programmersprefer the convenience of not having to use backslashes
which is offered bytriple quotes.
Threelines = ‘First\
Second\
Third’
Threelines = "First
Second
Third’”
Working with string :
#create string
>>>type(s)
#string concatenation
>>>t= “this is sample program.”
>>>r=stt
>>>r
‘Hello World! This is sample program.’
#get length of string
>>>len (s)
12
#print string
>>>print s
Hello World!
List DataLists provide a general mechanism for storing a collection of objects
indexedby a number in python. The elements of the list are arbitrary —
they can benumbers, strings, functions, user-defined objects or even other
lists, makingcomplex data structures very simple to express in python.
You can input alist to the python interpreter by surrounding a comma
separated list of theobjects you want in the list with square brackets ({ ])
Thus, a simple list ofnumbers can be created as follows:
>>>mylist = [1,7,9, 13, 22, 31]
Python ignores spaces between the entries of a list. If you need to
spanmultiple lines with a list entry, you can simply hit the return key after
anycomma in the list:
>>>newlist = [7, 9, 12, 15,
.. 17,19,103]
Note that the python interpreter changes its prompt when it recognizes
acontinuation line, and that no indentation is necessary to continue a line
likethis. Inside a script, your input can also be broken up after commas in
asimilar fashion. To create an empty list, use square brackets with no
elementsin between them ([]).The elements of a list need not be of the
same type. The following listcontains numeric, string and list data, along
with a function:
>>>mixlist = [7,'dog’,'tree’,[1,5,2,7],abs]
Working with lists:
>>>fruits=['apple’, ‘orange’ , ‘banana’, ‘mango’]
>>>type(fruits)
>>>len(fruits)
4
>>>fruits[1]
‘orange’
>>>fruits [1:]
orange’, ‘banana’ ,"mango’]
#appending an item to list
>>>fruits.append(‘pear’)
>>>fruits
U'apple’, ‘orange’ , ‘banana’, ‘mango’, ‘pear’]#Removing an item from list
>>>fruits.remove('mango’)
>>>fruits
[‘apple’, ‘orange’ , ‘banana’, ‘pear’]
#Inserting an item to list
>>>fruits.insert (1,mango’)
>>>fruits
[‘apple’, ‘mango’, ‘orange’, ‘banana’, ‘pear’]
#combining lists
>>>vegetables=[‘potato’, ‘carrot’, ‘onion’]
>>>vegetables
>>>eatables=fruits+vegatables
>>>l[‘apple’, ‘mango’, ‘orange’, ‘banana’, ‘pear’, ' potato’, ‘carrot’, ‘onion’
Tuple Objects
Tuples are very much like lists, except for one important difference.
Whilelists are mutable, tuples, like strings, are not. This means that, once
a tupleis created, its elements can’t be modified in place. Knowing that a
tuple isimmutable, python can be more efficient in manipulating tuples
than lists,whose contents can change at any time, so when you know you
won't needto change the elements within a sequence, it may be more
efficient to use atuple instead of a list. In addition, there are a number of
situations (argumentpassing and string formatting for example) where
tuples are required.Tuples are created in a similar fashion to lists, except
that there is noneed for square brackets surrounding the value. When the
python interpreter displays a tuple, it always surrounds it with
parentheses; you can useparentheses when inputting a tuple, but it’s not
necessary unless the tuple ispart of an expression. This creates a slight
syntactic problem when creatinga tuple with either zero or one element;
python will not know you're creatinga tuple, For an empty (zero-element)
tuple, a pair of empty parentheseis (())can be used. But surrounding the
value with parentheses is not enough inthe case of a tuple with exactly
one element, since parentheses are used forgrouping in arithmetic
expression. To specify a tuple with only one elementin an assignment
statement, simply follow the element with a comma, arithmetic
expressions, you need to surround it with parentheses, and followthe
element with a comma before the closing parenthesis.Working with Tuple:
>>>fruits=(‘apple’, ‘orange’ , ‘banana’, ‘mango’)
>>>type(fruits)
>>>len(fruits)
4
>>>fruits[0]
‘apple’
>>>fruits [:3]
apple’, ‘orange’, ‘banana’)
Dictionaries
Dictionaries (sometimes refered to as associative arrays or hashes) are
verysimilar to lists in that they can contain arbitrary objects and can be
nestedto any desired depth, but, instead of being indexed by integers,
they can beindexed by any immutable object, such as strings or tuples.
Since humans canmore easily associate information with strings than with
arbitrary numbers,dictionaries are an especially convenient way to keep
track of informationwithin a program.As a simple example of a dictionary,
consider a phonebook. We couldstore phone numbers as tuples inside a
list, with the first tuple element beingthe name of the person and the
second tuple element being the phone number:
>>>phonelist = ((‘Fred’,'555-1231'),(’Andy’,’555-1195’),("Sue’,’555-
2193')]
However, to find, say, Sue's phone number, we'd have to search each
elementof the list to find the tuple with Sue as the first element in order to
find thenumber we wanted. With a dictionary, we can use the person’s
name as theindex to the array. In this case, the index is usually refered to
as a key. Thismakes it very easy to find the information we're looking for:
>>>phonedict = {'Fred’:'555-1231’,'Andy’:’555-1195’,’Sue’:’555-2193'}
>>>phonedict[’Sue’]
"555-2193"
As the above example illustrates, we can initialize a dictionary with a
comma-separated list of key/value pairs, separated by colons, andsurrounded bycurly braces. An empty dictionary can be expressed by a
set of empty curlybraces ({}).
Working with dictionaries:
>>>student={‘name’:'Mary’, ‘id’: ‘4033’, ‘year’: '3’}
>>>student
>>>type (student)
#get length of dictionary
>>>len(student)
3
# Get value of key in dictionary
>>>student [‘name’]
‘Mary’
# Get all key in dictionary
>>>student.keys()
[ ‘name’, ‘id’, ‘year’]
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 ifelse statement is used in Python for decision making.
Syntax
if test expression
Body of ifelse:
Body of else
The if 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.Ise Statement flow chart:
if false
condition
true
body of if body of else
Example of if...else
# 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 if is 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 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 me
True
x
Body of if
Figs Operation of if statement
Example: Python if Statement
# If the number is positive, we print an appropriate message
num =if num> 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
variablenum 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 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...elif...elsecoat =
boul of it
| tue
body of elit body of else
Example of if...elif...else
# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = 3.4# Try these two variations as well
#num=0
# num =-4.5
print("Positive 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 can.
Python Nested if Example
# In this 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: "))
print("Zero")
@ o
2 g
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative 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
Start
Has Loop
Reached
Last item
—— Stop Loop
Print
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:
sum = sum+val
# Output: The sum is 48print("The sum is", sum)
when you run the program, the output will be:
The sum is 48
Introduction to raspberry pi
The Raspberry Pi is a remarkable device: a fully functional computer in a
tiny and low-cost package. Whether you're looking for a device you can
use to browse theweb or play games, are interested in learning how to
write your own programs, or arelooking to create your own circuits and
physical devices, the Raspberry Pi - and its amazingcommunity - will
support you every step of the way.The Raspberry Pi is known as a single-
board computer, which means exactly what it soundslike: it's a computer,
just like a desktop, laptop, or smartphone, but built on a single
printedcircuit board. Like most single-board computers, the Raspberry Pi
is small - roughly the samefootprint as a credit card - but that doesn’t
mean it's not powerful: a Raspberry Pi can doanything a bigger and more
power-hungry computer can do, though not necessarily as quickly.The
Raspberry Pi family was born from a desire to encourage more hands-on
computereducation around the world. Its creators, who joined together to
form the non-profit RaspberryPi Foundation, had little idea that it would
prove so popular: the few thousand built in 2012 totest the waters were
immediately sold out, and millions have been shipped all over the worldin
the years since. These boards have found their ways into homes,
classrooms, offices, datacentres, factories, and even self-piloting boats
and spacefaring balloons.Various models of Raspberry Pi have been
released since the original Model B, eachbringing either improved
specifications or features specific to a particular use-case. TheRaspberry
Pi Zero family, for example, is a tiny version of the full-size Raspberry Pi
whichdrops a few features - in particular the multiple USB ports and wired
network port - in favourof a significantly smaller layout and lowered
power needs.aT
LU
Figure:1 raspberry pi
While it may look likethere’s a lot packed into thetiny board, the
RaspberryPi isvery simple to understand -starting with its components,the
inner workings that makethe device tickThis includes the central
processing unit (CPU), commonly thought ofas the ‘brain’ of a computer,
and the graphics processing unit (GPU), which handles the visualside of
things.A brain is no good without memory, however, and on the underside
of the Raspberry Pi you'llfind exactly that: another chip, which looks like a
small, black, plastic square. Thisis the Pi's random access memory (RAM).
When you're working on the Pi, it’s the RAM thatholds what you're doing;
only when you save your work will it be written to the microSD
card.Together, these components form the Pi’s volatile and non-volatile
memories: the volatile RAMloses its contents whenever the Pi is powered
off, while the non-volatile microSD card keepsits contents.Turning the
board over again you'll find another metal lid to the upper-right, this
onefeaturing an etched Raspberry Pi logo (Figure, overleaf). This covers
the radio, thecomponent which gives the Raspberry Pi the ability to
communicate with devices wirelessly.The radio itself acts as two main
components, in fact: a WiFi radio, for connecting to computernetworks;
and a Bluetooth radio, for connecting to peripherals like mice and for
sending data toor receiving data from nearby smart devices like sensors
or smartphones.Another black, plastic-covered chip can be seen to the
bottom edge of the board, just behindthe middle set of USB ports. This is
the network and USB controller, and is responsible forrunning the Ethernet
port and the four USB ports. A final black chip, much smaller than the
rest,can be found a little bit above the micro USB power connector to the
upper-left of the board(Figure 1); this is known as a power managementintegrated circuit (PMIC), and handles turningthe power that comes in
from the micro USB port into the power the Pi needs to run.
RASPBERRY PI
ARMIL/BIZES ARM. Core
wo) onevevesiyze
IPNETWORK,
{paw DRIVER
; cK?
(sas
Excode/Dccoder
Figure:2 raspberry pi -block diagram
Features of Raspberry Pi:
+ Raspberry Pi is a low-cost mini-computer with the physical size of
acredit card.
+ Raspberry Pi runs various flavors of Linux and can perform almost
alltasks that a normal desktop computer can do.
+ Raspberry Pi also allows interfacing sensors and actuators throughthe
general purpose 1/0 pins.
+ Since Raspberry Pi runs Linux operating system, it supports Python"out
of the box"
The Raspberry
's ports
The Raspberry Pi has a range of ports, starting with four Universal Serial
Bus (USB) ports(Figure 2) to the middle and right-hand side of the bottom
edge. These ports let you connectany USB-compatible peripheral, from
keyboards and mice to digital cameras and flash drives,to the Pi. Speakingtechnically, these are known as USB 2.0 ports, which means they are
basedon version two of the Universal Serial Bus standard
To the left of the USB ports is an Ethernet port, also known as a network
port (Figure above).You can use this port to connect the Raspberry Pi to a
wired computer network using a cablewith what is known as an Rj45
connector on its end. If you look closely at the Ethernet port,you’ll see two
light-emitting diodes (LEDs) at the bottom; these are status LEDs, and let
youknow that the connection is working.Just above the Ethernet port, on
the left-hand edge of the Raspberry Pi, is a 3.5 mmaudio-visual (AV) jack
(Figure 2). This is also known as the headphone jack, and it can be usedfor
that exact purpose - though you'll get better sound connecting it to
amplified speakers ratherthan headphones. It has a hidden, extra feature,
though: as well as audio, the 3.5 mm AV jackcarries a video signal which
can be connected to TVs, projectors, and other displays.
High-Definition Multimedia Interface (HDMI) port:
It is the same type of connector you'll find on a gamesconsole, set-top
box, and TV. The multimedia part of its name tells you that it carries
bothaudio and video signals, while high-definition tells you that you can
expect excellent quality.You'll use this to connect the Raspberry Pi to your
display device, whether that’s a computermonitor, TV, or projector.Micro USB power port: which you'll use to connectthe Raspberry Pi to a
power source. The micro USB port is a common sight on
smartphones,tablets, and other portable devices. So you could use a
standard mobile charger to power thePi, but for best results you should
use the official Raspberry Pi USB Power Supply.
Raspberry
's peripherals
A Raspberry Pi by itself can’t do very much, just the same as a desktop
computer on its ownis little more than a door-stop. To work, the Raspberry
Pi needs peripherals: at the minimum,you'll need a microSD card for
storage; a monitor or TV so you can see what you're doing; akeyboard and
mouse to tell the Pi what to do; and a 5 volt (5 V) micro USB power supply
ratedat 2.5 amps (2.5 A) or better. With those, you've got yourself a fully
functional computer.
USB power supply: A power supply ratedat 2.5 amps (2.5A) or 12.5
watts (12.5W)and with a micro USB connector. TheOfficial Raspberry Pi
Power Supply is therecommended choice, as it can cope withthe quickly
switching power demands ofthe Raspberry Pi.
Raspberry Pi General purpose Input/Output(GPIO)
Pind Pin2
+33 +5v
GPI02 / SAL 45
GPI03 / SCL eno
PI04 TxDO/GPIO 14
eno RXDO/ GPIO 15,
P1017 PI0 18
cp1027 eno
sP1022 GrI0 23,
433 GPI0 24
GPI010 / Most ono
GPI09 / Miso P10 25
pion j scux cE0# /GPI08
eno ceL# / GPIO7
Pin25 Pin 26
The GPIO pins on the Raspberry Pi are divided into the follor
groups:Power: Pins that are labeled 5.0v supply 5 volts of power and those
labeled 3V3 supply 3.3 volts of power. There are two 5V pins and two 3V3
pins.
GND: These are the ground pins. There are eight ground pins.
Input/Output pins: These are the pins labelled with the # sign, for
example, #17, #27, #22, etc. These pins can be used for input or output.
UART: The Universal Asynchronous Receiver/Transmitter allows your
Raspberry Pi to be connected to serial peripherals. The UART pins are
labelled TXD and RXD.
SPI: The Serial Peripheral Interface is a synchronous serial communication
interface specification used for short distance communication, primarily in
embedded systems. The SPI pins are labeled MOSI, MISO, SCLK, CEO, and
Cel.
+ Miso(Master In Slave Out): Master line for sending data to the
master.
* MOSI(MasterOut Slave In): Slave line for sending data to the
Peripherals.
+ SCK( Serial Clock): Clock generated by master to synchronize data
transmission.
+ CEO( chip Enable 0): to enable or disable devices
+ CE1( chip Enable 1): to enable or disable devices.
ID EEPROM: Electrically Erasable Programmable Read-Only Memory is a
user-modifiable read-only memory that can be erased and written to
repeatedly through the application of higher than normal electrical
voltage. The two EEPROM pins on the Raspberry Pi (EED and EEC) are also
secondary |2C ports that primarily facilitate the identification of Pi Plates
(e.g., Raspberry Pi Shields/Add-On Boards) that are directly attached to
the Raspberry Pi.SPI(Serial peripheral interface)
12€ (Inter Integrated chip)
The I2C interface pins on raspberry pi allow you to connect hardware
modules. |2C interface allow synchronous data transfer with two pins -
SDA( data line) and SCL(clock line)
Serial
The serial interface on Raspberry Pi has receive (Rx) and Transmit (Tx)
pins for communication with serial periperals.Interfacing Raspberry Pi with basic peripherals:
In this section you will learn how to get started with developing python
programs on Raspberry Pi. Raspberry Pi runs Linux and supports Python
out of box. Therefore, you can run any python program which runs on
normal computer. However, it is the general purpose input/output
pins(GPIO) on Raspberry Pi that makes it useful for loT, We can interface
Raspberry Pi with sensors and actuators with GPIO pins and SPI, 12C and
serial interfaces.
Controlling LED with Raspberry Pi
Let us start with basic example of controlling an LED from Raspberry Pi. In
this example the LED is connected to GPIO pin 18. We can connect LED to
other GPIO pin as well.
The program uses the RPi.GPIO module to control the GPIO on Raspberry
Pi. In this program we set pin 18 direction to output and then True/False
alternatively after a delay of one second.
To begin, we import the GPIO package that we will need so that we can
communicate with the GPIO pins.We also import the time package, so
we're able to put the script to sleep for when we need to.We then set the
GPIO mode to GPIO.BOARD/GPIO.BCM, and this means all the numbering
we use in this script will refer to the physical numbering of the pins.
Program
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import §1€ép# Import the sleep function from the time module
GPIOSetmMode(GPIO/BCM/BOARD) # Use physical pin numbering
GPIO.setup(18, GPIO.OUT) # Set pin 18 to be an output pin
while True: # Run forever
GPIO.output(18, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(18, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second
Interfacing an LED and Switch with Raspberry Pi
In this example the LED is connected to GPIO pin 18 and the switch is
connected to pin 13. In the infinite while loop the value of pin 13 is
checked and the state of LED is toggled if the switch is pressed. Thisexample shows how to get input from GPIO pins and process the input and
take some actions.
Program
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(13,GPIO.IN) #button
GPIO.setup(18,GPIO.0UT) #led
while True:
if (GPIO.input(13)):
print("on")
GP|O.output(18, GPIO.HIGH)
while False:
if (GPIO.input(13)):
print(“off”)
GP1O.output(18, GPIO.LOW)
Interfacing Light Dependent Resistor (LDR) in Raspberry Pi:
This is code for interfacing LDR in Raspberry Pi. First of all, we have to
import the Light Sensor code for LDR from the GPIOZERO library. Assign
GPIO pin to variable LDR and also pass the GPIO pin number as an
argument to the LightSensor method. While loop print's value of LDR.
Program:
from gpiozero import LightSensor
LDR = LightSensor (4) _ # light sensor given to pin 4
while True:
print(Idr.value)Python program for switching LED based on LDR readings:
Since we only have one input/output pin, we only need to set one variable.
Set this variable to the number of the pin you have acting as the
input/output pin.Next, we have a function called ré_time that requires one
parameter, which is the pin number to the circuit. In this function, we
initialize a variable called count, and we will return this value once the pin
goes to high.We then set our pin to act as an output and then set it to low.
Next, we have the script sleep for 10ms.After this, we then set the pin to
become an input, and then we enter a while loop. We stay in this loop
until the pin goes to high, this is when the capacitor charges to about
3/4.0nce the pin goes high, we return the count value to the main
function. You can use this value to turn on and off an LED, activate
something else, or log the data and keep statistics on any variance in
light.
Program:
import RPi,GPIO as GPIO
import time import sleep
def rc_time (pin_to_circuit)
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
sleep(1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit)
GPIO.LOW):
count += 1
retum countImplementation of loT with Raspberry Pi
Why it i
The Internet of Things (loT) is a scenario in which objects, animals or
people are provided with single identifiers and the capability to
automatically transfer and the capability to automatically transfer data
more to a network without requiring human-to-human or human-to-
computer communication. loT has evolved from the meeting of wireless
technologies, micro-electromechanical systems (MEMS) and the
internet.-The Raspberry Pi is a popular choice when developing loT
products. It offers a complete Linux server with a tiny platform at an
incredibly low price. Actually, the Raspberry Pi is so well-known to loT that
the company has featured several Internet of Things projects on their site.
Here you will find projects and community support for a range of loT
activities. Take for example, the World's First Cloud Texting Enabled
Espresso Machine - powered by Raspberry Pi.Partnered with the Zipwhip
cloud texting application, the Raspberry Pi connects to an espresso
machine and allows people to text a message to it that automatically
turns it on and starts brewing beverages. Raspberry Pi can be plugged
into a TV, computer monitor, and it uses a standard keyboard and mouse.
It is user-friendly as it can be handled by all the age groups. It does
everything you would expect a desktop computer to do like word-
processing, browsing the internet spreadsheets, playing games to playing
high definition videos. It is used in many applications like in a wide array
of digital maker projects, music machines, parent detectors to the
weather station and tweeting birdhouses with infrared cameras.All models
feature on a Broadcom system on a chip (SOC), which includes chip
graphics processing unit GPU(a Video Core IV), an ARM-compatible and
CPU. The CPU speed ranges from 700 MHz to 1.2 GHz for the Pi 3 and
onboard memory range from 256 MB to 1 GB RAM. An operating system is
stored in the secured digital SD cards and program memory in either the
MicroSDHC or SDHC sizes. Most boards have one to four USB slots,
composite video output, HDMI and a 3.5 mm phone jack for audio. Some
models have WiFi and Bluetooth.
important for loT:
Python program for using PIR sensor:Connecting to a Sensor to Detect Motion
To demonstrate how to use the GPIO to connect to an external sensor,
we'll now use a PIR motion sensor to detect motion. For this, | used the
PIR Motion Sensor
+9V|
Output
GND
Parallax PIR Motion Sensor (see fig). The PIR Sensor detects motion by
measuring changes in the infrared (heat) levels emitted by surrounding
objects of up to three meters.
The Parallax Motion sensor has three pins (see Figure ):
GND: The Ground pin. Connect this pin to the GND on the GPIO.
VCC: The voltage pin. Connect this pin to one of the SV pins on the GPIO.
OUT: The output pin, Connect this to one of the Input/Output pins on the
Plo
import RPi.GPIO as GPIO #1
import time #2
pirsensor = 4 #3
GPIO.setmode(GPIO.BCM) #4
GPIO.setup(pirsensor, GPIO.IN) #5
previous_state = False #6
current_state = Falsewhile True: a7
time.sleep(0.1) #8
previous_state = current_state #9
current_state = GPIO.input(pirsensor) #10
if current_state != previous_state: #11
if current_state: #12
print("Motion not Detected!") #13
#1: The latest version of Raspbian includes the RPI.GPIO Python library
pre-installed, so you can simply import that into your Python code. The
RPI.GPIO is a library that allows your Python application to easily access
the GPIO pins on your Raspberry Pi. The as keyword in Python allows you
to refer to the RPI.GPIO library using the shorter name of GPIO.
#2: The application is going to insert some delays in the execution, so you
need to import the time module.
#3: You declare a variable named pirsensor to indicate the pin number for
which the Output pin on the PIR sensor is connected to the GPIO pin. In
this example, it's GPIO pin #4.
#4: There are two ways to refer to the pins on the GPIO: either by physical
pin numbers (starting from pin 1 to 40 on the Raspberry Pi 2/3), or
Broadcom GPIO numbers (BCM). Using BCM is very useful with a ribbon
cable (such as the Adafruit T-Cobbler Plus) to connect the Raspberry Pi to
the breadboard. The BCM numbers refer to the labels printed on the T-
Cobbler Plus (see Figure 8). For this example, we're using the BCM
numbering scheme. That means that when we say we're getting the input
from pin 4, we're referring to the pin printed as #4 on the T-Cobbler Plus.
#5: Initialize the pin represented by the variable pinsensor as an input
pin. Also, we use a pull-down resistor (GPIO.PUD_DOWN) for this pin.
#6: There are two variables to keep track of the state of the sensor.
#7: We use an infinite loop to check the state of the sensor repeatedly.
#8: Inserts a slight delay of 1 second to the execution of the program
#9: Save the current state of the sensor.
#10: The GPIO.input() function reads the value of the GPIO pin (#4 in this
case). When motion is detected, it returns a value of true.#11: Compare the previous state and the current state to see if the
motion sensor has a change in state. If there's a change, it means that
either the sensor has just detected motion (when the state changes from
false to true), or that the sensor is resetting itself (when the state changes
from true to false) a few seconds after motion has been detected
#12: If the current state is true, it means that motion has been detected.
#13: Print out the string “Motion Detected!”
DHT11 Temperature and Humidity Sensor and the Raspberry Pi
The DHT11 requires a specific protocol to be applied to the data pin. In
order to save time trying to implement this yourself it’s far easier to use
the Adafruit DHT library.The library deals with the data that needs to be
exchanged with the sensor but it is sensitive to timing issues. The Pi's
operating system may get in the way while performing other tasks so to
compensate for this the library requests a number of readings from the
device until it gets one that is valid.
program:
import RPi.GPIO as GPIO
# Set sensor type : Options are DHT11,DHT22 or AM2302
sensor=Adafruit_DHT.DHT11
gpio=17
# Use read_retry method. This will retry up to 15 times to get a sensor
reading (waiting 2 seconds between each retry)
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
# Reading the DHT11 is very sensitive to timings and occasionally the Pi
might fail to get a valid reading. So check if readings are valid.
if humidity is not None and temperature is not None:print(‘Temp={0:0.1f}*C
Humidity={1:0.1f}
%' format(temperature,
humidity))
else:
print(‘Failed to get reading, Try again!)
The DHT11 is probably best suited for
projects where rapid data readings are not required and the environment
is not expected to see sudden changes in temperature or humidity. A
weather station would be an idea project but a central heating controller
may require something different.
Motors programming:
Import RPi.GPIO as GPIO
motor1 = Motor(4, 14) #to make it easier to see which pin is which,
you can use Motor(forward=4, backward=14) .
motor2 = Motor(17, 27) # forward=17, backward =27
motor1.forward()
motor2.forward()
motor1.backward()
motor2.backward()while True: #The Motor class also allows you to reverse themotor’s
direction.
sleep(5)
motor1.reverse()
motor2.reverse()
motor1.stop() # Now stop the motors
motor2.stop()
Buzzer program:
from gpiozero import Button,Lights, buzzer.
buzzer = Buzzer(15)
while True:
lights.on()
buzzer.on()
button.wait_for_press()
lights. off()
buzzer.off()
button.wait_for_release()
Traffic lights program:
from gpiozero import, Button, TrafficLights
from time import sleep
while True:
lights.green.on()
sleep(1)
lights. orange.on()
sleep(1)
lights.red.on()
sleep(1)
lights. off()Add a wait_for_press so that pressing the button ini
sequence
iates the
Try adding the button for a pedestrian crossing. The button should move
the lights to red (not immediately), and give the pedestrians time to cross
before moving back to green until the button is pressed again.
Program:
while True:
button.wait_for_press()
lights.green.on()
sleep(1)
lights.amber.on()
sleep(1)
lights.red.on()
sleep(1)
lights. off()
Unit-4
Implementation of loT using Raspberry pi
Smart_Health:
The Internet of things is the inter-connection of devices, apps,sensors and
network connectivity that enhances these entitiesto gather and exchange
data. The distinguishing characteristicof Internet of Things in the
healthcare system is the constantmonitoring a patient through checking
various parameters andalso infers a good result from the history of such
constantmonitoring. Many such devices equipped with medicalsensors are
present in the ICUs now-a-days. There could beinstances where the doctor
couldn't be alerted in time whenthere is an emergency, despite of 24
hours of monitoring. Alsothere might be hurdles in sharing the data and
informationwith the specialist doctors and the concerned family
membersand relatives.
The most tremendous use of IoT is in healthcare management which
provides health and environment condition tracking facilities. loT is
nothing but linking computers to the internet utilizing sensors and
networks [9, 10]. These connected components can be used on devices