0% found this document useful (0 votes)
3 views22 pages

FIoT Unit-3

This document provides an overview of Python programming, including its history, data types, control flow statements, data structures, and functions. It also introduces Raspberry Pi and its interfacing with basic peripherals for IoT implementation. The content is structured to facilitate understanding of Python's capabilities and applications in IoT projects.

Uploaded by

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

FIoT Unit-3

This document provides an overview of Python programming, including its history, data types, control flow statements, data structures, and functions. It also introduces Raspberry Pi and its interfacing with basic peripherals for IoT implementation. The content is structured to facilitate understanding of Python's capabilities and applications in IoT projects.

Uploaded by

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

FUNDAMENTALS OF INTERNET OF THINGS(IoT)

Unit-III: Introduction to Python Programming, Introduction to Rasberry Pi, Interfacing


Rasberry Pi with basic peripherals, Implementation of IoT with Rasberry Pi

* Introduction to Python Programming*


History of the Python programming language was conceived in the late 1980s and its
implementation was started in December 1989 by Guido van Rossum, a Dutch programmer at
CWI in the Netherlands. Rossum published the first version of Python code (0.90.) in Feb 1991
in Netherlands.
Python is derived from ABC programming language, which is a general-purpose
programming language that had been developed at CWI. Rossum choose the name “Python”,
since he was a big fan of Monty Pyhton’s Flying Circus.
Python is an interpreted high-level programming language for general-purpose
programming. Its design philosophy emphasizes code readability, and its syntax allows
programmers to express concepts in fewer lines of code.

Python supports multiple programming paradigms, including object-oriented, imperative


and functional programming or procedural styles. It features a dynamic type system and
automatic memory management and has a large and comprehensive standard library.
Python is an object-oriented programming (OOP) language. Data in Python are objects
created from classes. Python is an Open source and Community based development model.
Generally, Python is called as Scripting language but has many other features.
The following are applications of Python Programming:

Procedure to Install and Run programs in Python:


In order to install python, Visit https://www.python.org. When we visit the Python for Windows
download page, we will immediately see the division. Right at the top, square and center, the
repository asks if you want the latest release of Python 2 or Python 3 (2.7.13 and 3.6.1, respectively)
as shown in below Figure.

The version we want depends on our end goal.


Datatypes:
Python provides built-in data types. There is no need to define data type of a variable.
Every value in Python has a data type. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.

Data type is classified into Immutable and Mutable. In general, data types in Python can be
distinguished based on whether objects of the type are mutable or immutable.
 Immutable:

The content of objects of immutable types cannot be changed after they are created.

Example:

 int, float, long, complex


 str
 bytes
 tuple
 frozen set

a) Numbers: Number data types store numeric values. Number objects are created when you
assign a value to them.

Example:

>>> num1 = 24
>>>num2 = 89.6
>>>type(num1)
<class ‘int’>
>>>type(num2)
<class ‘float’>
Python supports four different numerical types :

 int (signed integers)


 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)Here are some examples of numbers –

Example:
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))

Output:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True

b) Strings: Strings in Python are identified as a contiguous set of characters (sequences)


represented in the quotation marks. Python allows for either pairs of single or double
quotes.

Example 1:

Sample1=’Welcome to Python Programming’


Sample2=”Welcome to Python Programming”
Sample3=”””Python is an object oriented programming language.
Python is easy to learn”””
Example2:
>>>s=str(3.6)
>>>s
‘3.6’
>>>s=str(10)
>>>s
‘10’
>>>
String Indexing:
The benefit of using String is that it can be accessed from both the directions in forward and
backward.
Both forward as well as backward indexing are provided using Strings in Python.
 Forward indexing starts with 0,1,2,3,....
 Backward indexing starts with -1,-2,-3,-4,....

c) Tuples: A tuple is a sequence of immutable objects, therefore tuple cannot be changed. The
objects are enclosed within parenthesis and separated by comma. Creating a tuple is as
simple as putting different comma-separated values.

Example:
tup1 = ('python', 'programming', 1000, 2000);
tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing –


tup1 = ();

For a single valued tuple, there must be a comma at the end of the value.
tup1 = (50,);
Accessing Values in Tuples:

To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index.

Example:
tup1 = ('python', 'programming', 1000, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]

Output:
tup1[0]: python

tup2[1:5]: [2, 3, 4, 5]

 Mutable:

Only mutable objects support methods that change the object in place, such as reassignment of a
sequence slice, which will work for lists, but raise an error for tuples and strings.

Example:

 byte array
 list
 set
 dict

a) Lists: A list can be created by putting the value inside the square bracket and separated
by comma. Important thing about a list is that items in a list need not be of the same type.

Syntax:

<list_name>=[value1,value2,value3,……,valuen];

For accessing list:


<list_name>[index]

Example:
>>>numbers= [2,3,4,5,6]

>>>numbers

[2,3,4,5,6]

b) Dictionaries: Dictionary is an unordered set of key and value pair. It is an container that
contains data, enclosed within curly braces. The pair i.e., key and value is known as item.
The key passed in the item must be unique. The key and the value is separated by a
colon(:). This pair is known as item. Items are separated from each other by a comma(,).
Different items are enclosed within a curly brace and this forms Dictionary.

Accessing Values in Dictionary:


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

c) Sets: A set is an unordered collection of items. Every element is unique (no duplicates)
and must be immutable (which cannot be changed). However, the set itself is mutable.
We can add or remove items from it. Sets can be used to perform mathematical set
operations like union, intersection, symmetric difference etc.

Example:

#set of integers
my_set={1,2,3}
print(my_set)

#set of mixed datatypes

my_set={1.0,”Hello”,(1,2,3)}
print(my_set)
Control Flow Statements:
To write the useful programs, we always need the ability to check the conditions and change the
behavior of the program accordingly. A conditional statement makes a choice to test an
expression whether it is True or Flase.

 if statement:

The if statement in python is same as c language which is used test a condition. If condition is
true, statement of if block is executed otherwise else block is executed by default.
Example

year=2000
if year%4==0:
print "Year is Leap"
else:
print "Year is not Leap"
Output:
Year is Leap

 if-elif-else statement:

The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.
Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case.
Example:
marks=70
if(marks>80):
print(“Grade A”)
elif(marks>60) and (marks<=80):
print(“Grade B”)
elif(marks>40) and (marks<=60):
print(“Grade C”)
else:
print(“Grade D”)

 for loop:
for Loop is used to iterate a variable over a sequence(i.e., list or string) in the order that
they appear.

Example:

num=2
for a in range (1,6):
print num * a

Output:

2
4
6
8
10

 while loop:

while Loop is used to execute number of statements or body till the condition passed in while is
true. Once the condition is false, the control will come out of the loop.
Example:

a=10
while a>0:
print "Value of a is",a
a=a-2
Output:

>>>
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
>>>

 break statement:

break statement is a jump statement that is used to pass the control to the end of the loop. When
break statement is applied the control points to the line following the body of the loop ,hence
applying break statement makes the loop to terminate and controls goes to next line pointing
after loop body.
Example:

for letter in 'Python': # First Example


if letter == 'h':
break
print 'Current Letter :', letter

Output:

Current Letter : P
Current Letter : y
Current Letter : t

 continue statement:

continue Statement is a jump statement that is used to skip the present iteration and forces next
iteration of loop to take place. It can be used in while as well as for loop statements.
Example:

for letter in 'Python': # First Example


if letter == 'h':
continue
print 'Current Letter :', letter

Output:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

 pass statement:

The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute. The pass statement is a null operation; nothing happens
when it executes.

Example:

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

print "Good bye!"

Output:

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Data Structures:
In computer science, Data Structures are a way of organizing and storing data so that they can
be accessed and worked with efficiently. They define the relationship between the data, and the
operations that can be performed on the data.
There are various kinds of data structures defined that make it easier for the data scientists and
the computer engineers, alike to concentrate on the main picture of solving larger problems
rather than getting lost in the details of data description and access.
There are two types of Data Structures:
1. Built-in Data Structure: They are provided by default.
(a) List, Strings, Tuple, Dictionary, Sets.
2. User-defined Data Structure: They are designed for a particular task.
(b) Stack, Queue…

LIST
A List is an ordered collection of items. Lists are used to store collection of
heterogeneous items. General purpose widely used data structure. List supports sequence type.
List constants are surrounded by square brackets [ ] and the elements in the list are separated by
commas.These are mutable, which means that you can change their content without changing
their identity.
Creating Lists:
TUPLES
A Tuple is a sequence of immutable objects. Tuple are sequences of heterogeneous
elements. Any constant data that won’t change, better to use tuple. Once a Tuple is created, you
cannot add new elements, delete elements, replace elements, or reorder the elements in the
tuples. A tuple is faster than list. A Tuple is a sequence type and nested type.
A tuple is very much like a list, except that its elements are fixed. Furthermore, tuples are more
efficient than lists due to
Python’s implementations.

Creating a Tuple:

You create a tuple by enclosing its elements inside a pair of parentheses. The elements are
separated by commas. You can create an empty tuple and create a tuple from a list, as shown in
the following example:

SETS

A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).However, the set itself is mutable. We can add or remove
items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
Create a Set:

A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().
It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.

Example:

DICTIONARIES

Python dictionary is an unordered collection of items. While other compound data types have
only value as an element, a dictionary has a key: value pair.

Dictionaries are optimized to retrieve values when the key is known.

Create and Access a dictionary:

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.

While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.

Example:
FUNCTIONS
Introduction:
A Function is a self block of code. A Function can be called as a section of a program that is
written once and can be executed whenever required in the program, thus making code
reusability.
A Function is a subpgroup of related statements that perform a specific task.
Types of Functions:
There are two types of Functions.
a) Built-in Functions: Functions that are predefined. We have used many predefined functions in
Python.
b) User- Defined: Functions that are created according to the requirements.
Defining Function:
A Function defined in Python should follow the following format:
1) Keyword def is used to start the Function Definition. def specifies the starting of Function
block.
2) def is followed by function-name followed by parenthesis.
3) Parameters are passed inside the parenthesis. At the end a colon is marked.
A function contains a header and body. The header begins with the def keyword, followed by the
function’s name and parameters, and ends with a colon.
The variables in the function header are known as formal parameters or simply parameters. A
parameter is like a placeholder: When a function is invoked, you pass a value to the parameter.
This value is referred to as an actual parameter or argument. Parameters are optional; that is, a
function may not have any parameters. For example, the random. random() function has no
parameters
Syntax:
def <function_name>([parameters]):
</function_name>
Example:
def sum(a,b):
Calling A Function / Invoking A Function:
To execute a function it needs to be called. This is called function calling. Function Definition
provides the information about function name, parameters and the definition what operation is to
be performed. In order to execute the Function Definition it is to be called.
Syntax:
<function_name>(parameters)
</function_name>
Example:
sum(a,b)
Here sum is the function and a, b are the parameters passed to the Function Definition.
Let us have a look over an example:
Example:
# Providing Function Definition
def sum(x,y):
"Going to add x and y" # doc_string#
s=x+y
print "Sum of two numbers is"
print s
#Calling the sum Function
sum(10,20)
sum(20,30)
Output:
>>>
Sum of two numbers is
30
Sum of two numbers is
50
>>>

*Introduction to Rasberry Pi*


 Raspberry Pi, developed by Raspberry Pi Foundation in association with Broadcom, is a
series of small single-board computers and perhaps the most inspiring computer available
today.
 Raspberry Pi is a low cost, credit-card sized computer that plugs into a computer monitor
TV and uses a standard keyboard and mouse.
 Programs are written in languages like Python, c, Java, Ruby.
 It is capable of doing everything we expect from a desktop computer. We can browse the
Internet, play high-definition video, to make spreadsheets, word-processing and playing
games.
 There are several generations of Raspberry Pi like Raspberry Pi 3 model B, Raspberry Pi
2 model B, Raspberry Pi zero.

Architecture:
 The basic set up for Raspberry Pi includes HDMI cable, monitor, keyboard, mouse, 5volt
power adapter for Raspberry Pi, LAN cable, 2 GB microSD card (minimum).
 Most commonly Pi. used programming languages in Raspberry Pi are Python, C, C++,
Java, Scratch and Ruby.
 The popular applications developed using Raspberry Pi are media streamer, home
automation, controlling robot, Virtual Private Network (VPN), light weight Web server
with IoT etc.

We can use the Raspberry Pi computer for the following −


 Playing games
 Browsing the internet
 Word processing
 Spreadsheets
 Editing photos
 Paying bills online
 Managing your accounts.
*Interfacing Raspberry Pi with basic peripherals*

LINUX ON RASPBERRY PI:

 Raspbian: Raspbian Linux is a Debian Wheezy port optimized for Raspberry Pi.
 Arch: Arch is an Arch Linux port for AMD devices.
 Pidora: Pidora Linux is a Fedora Linux optimized for Raspberry Pi.
 RaspBMC: RaspBMC is an XBMC media-center distribution for Raspberry Pi.
 OpenELEC: OpenELEC is a fast and user-friendly XBMC media-center distribution.
RISC OS: RISC OS is a very fast and compact operating system.

Pin Configuration:

 GPIO pins in pins in Raspberry Pi are the general-purpose Input-Output pins.


 GPIO pins allow the Raspberry Pi to control and monitor the outside world by being
connected to electronic circuits.
 These pins are to Communicate with other circuit such as such as extension boards,
custom circuits and much more.
 For getting an output, we can turn a GPIO pin HIGH or LOW.
 There are 40 pins on the Raspberry Pi (26 pins on early models), and they provide
various different functions.

Raspberry Pi Interfaces:
 Serial:
The serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins for
communication with serial peripherals.

 SPI:
Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for
communicating with one or more peripheral devices.

 I2C:
The I2C interface pins on Raspberry Pi allow you to connect hardware modules.
I2C interface allows synchronous data transfer with just two pins - SDA (data line) and
SCL (clockline).
Raspberry Pi Example: Interfacing LED and switch with Raspberry Pi

Program:
from time import sleeP
import RPi.GPIO asGPIO
GPIO.setmode(GPIO.BCM)
#Switch Pin GPIO.setup(25,GPIO.IN)
#LEDPin
GPIO.setup(18,GPIO.OUT)
state=false
deftoggleLED(pin):
state = not state
GPIO.output(pin,state)
whileTrue:
try:
if (GPIO.input(25) ==True):
toggleLED(pin)
sleep(.01)

exceptKeyboardInterrupt:
exit()

You might also like