Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views34 pages

Iot Unit Iii R22.

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 34

UNIT-III

3.1 Introduction to Python programming


python is a very popular programming language at present. It is among other
applications it is very much useful for embedded systems application development for
example, IoT based application development python is very popular and it is a
lightweight programming language. python is also very easy to learn; and also you
know python is supported by different embedded systems development platforms or
IoT development platforms such as raspberry pi.So, it supports different types of IoT
devices and also you know you do not need to take help
of complex libraries etcetera etcetera execution is faster and so, there were so many
different advantages because of which python based programming is very important
to learn particularly if you are interested in IoT based application development.
Python is a very versatile language the scripting is very easy it is very easy to write
the read the code and moreover it does not support strict rules for syntax. because it
supports an interface with a wide range of hardware platforms and moreover since it
is an open source platform. So, you have lots of libraries, lots of collaborative work. It
forms a strong backbone to build large applications.
The python IDE is like Arduino is a free and open source software. So, you
can write various codes integrated integrate various modules libraries and so on. It can
be easily integrated with windows, Linux and Mac machines. So, some examples of
python IDE is are Spyder, PyCharm and so on.

>>>print(“Hi, welcome to python!”)


Output:
“Hi, welcome to python!”
we just write print hi welcome to python or any other statement the output will
be “Hi, welcome to python!” So the syntax is pretty straight forward, no need to call
any libraries, no need of any main function, no need of any other functions.

if else statement.
If True:
Print(“Correct”)
Else
Print(“Error”)
if true then colon you have an indentation print ‘correct’ else then again you go back
else colon again indent print ‘error’.
So, this indentation policy has to be followed whenever you enter into a loop. So,
after one statement or this colon you have to give one tab space indentation.
In Python programming, the “else if” statement, often called “elif,” is a conditional
statement that allows you to specify multiple conditions to be evaluated sequentially.
It provides a way to execute different code blocks based on various conditions. The
“else if” statement is used when you have multiple mutually exclusive requirements
and want to perform other actions depending on the valid state.

Conditional statements are an integral part of programming, enabling us to


make decisions and control the flow of our code based on certain conditions. These
statements allow the program to evaluate whether a situation is true or false and
execute specific code blocks accordingly. One such conditional statement used in
Python is the “else if” statement, also known as “elif.”
The “else if” statement in Python provides a way to handle multiple conditions
sequentially. It allows us to specify a series of conditions to be evaluated one after
another and execute the corresponding code block when a condition is true.
x = 10
if x < 5:
print("x is less than 5")
elif x > 5:
print("x is greater than 5")
else:
print("x is equal to 5")

There are five data types in python.

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

1. Numbers
Numbers in Python refer to the numeric data types in Python programming.
Python supports three kinds of numeric data types: int, float, and complex.
Integers are numbers without decimal points.

num=5

type(num)

num=23475891

type(num)

Floats are numbers with decimal points.

num=5.4

type(num)
Complex numbers have real parts and imaginary parts.

num=2+5j

type(num)

num.real #Gives the real part of the complex number

num.imag #Gives the imaginary part of the complex number

Complex numbers store the real and imaginary parts as a float by default.

Numbers can also be negative, which you can store in a variable.

num=-423.31

print(num)
2. Strings
A string is a sequence of characters that can be a combination of letters,
numbers, and special characters. It can be declared in python by using single
quotes, double quotes, or even triple quotes.

a = 'This is a string'
print (a)
b = "This is a string"
print (b)
c= '''This is a string'''
print (c)
3. List
Lists are one of the most powerful data structures in python. Lists are
sequenced data types. In Python, an empty list is created using list()
function. They are just like the arrays declared in other languages. But the
most powerful thing is that list need not be always homogeneous. A single
list can contain strings, integers, as well as other objects.

# Declaring a list
L = [1, "a" , "string" , 1+2]
print L
#Adding an element in the list
L.append(6)
print L
#Deleting last element from a list
L.pop()
print (L)
#Displaying Second element of the list
print (L[1])
4. Tuples
A tuple is a sequence of immutable Python objects. Tuples are just like lists
with the exception that tuples cannot be changed once declared. Tuples are
usually faster than lists.

tup = (1, "a", "string", 1+2)


print(tup)

print(tup[1])

5. Dictionary:
A dictionary in Python is a data structure that stores the value in value:key pairs.
Example:
As you can see from the example, data is stored in key:value pairs in dictionaries,
which makes it easier to find values.
 Python3

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(Dict)

Controlling Statements

What are Control Statements in Python?

Control statements are an essential aspect of any programming language,


including Python. Control statements in Python are used to manage the flow
of execution of a program based on certain conditions.

Control statements in Python are a powerful tool for managing the flow of
execution. They allow developers to make decisions based on specific
conditions and modify the normal sequential flow of a program. By using
control statements effectively, developers can write more efficient and
effective code.

Types of Control Statements in Python

There are three types of control statements in Python.

Break Statement in Python

The break statement is used to terminate a loop, i.e., for loop, while loop, or nested
loop. When a break statement executes inside a loop, it immediately terminates the
loop and transfers control to the statement following the loop.

Syntax of Break Statement in Python


The syntax of break statement in Python is as follows:

while condition:
# statements

if condition:

break

# statements after break statement

In this syntax, the break statement is used inside a loop (while loop or for
loop). When the condition specified in the if statement is true, the break
statement is executed, and the control is transferred to the next statement
after the loop. This means that the loop is terminated, and the code
execution continues from the statement after the loop.

Example of Break Statement in Python


Here’s an example of the break statement in Python:

 Python

list_of_numbers = [1, 3, 7, 9, 11, 12, 13, 15]


for num in list_of_numbers:
if num % 2 == 0:
print("The first even number is:", num)
break

Output:

The first even number is: 12

Explanation:
In this example, we have a list called list_of_numbers. We want to find the
first even number in this list. We use a for loop to iterate over the list, and
inside the loop, we use an if statement to check if the current number is
even. If the current number is even, we print it as the first even number, and
we use the break statement to exit the loop.

Continue Statement in Python

The continue statement is used to skip a particular iteration of a loop when a specific
condition is met. When a continue statement is executed inside a loop, it skips the
current iteration of the loop and jumps to the next iteration.

Syntax of Continue Statement in Python


The syntax for the continue statement in Python is as follows:

while condition:
# statements before the continue statement
if condition:
continue
# statements after the continue statement
In this syntax, when the condition specified in the if statement is true, the
continue statement is executed, and the control is transferred to the next
iteration of the loop. This means that the current iteration is skipped, and the
loop continues with the next iteration.

Example of Continue Statement in Python


Here’s an example of the continue statement in Python:

 Python

numbers = [1, 3, 7, 8, 9, 11, 12, 15]


for num in numbers:
if num % 2 == 0:
continue
print(num)

Output:

1
3
7
9
11
15
Explanation: We have a list of integers called numbers. Only the odd
numbers from this list should be printed. We use a for loop to traverse
through the list, and an if statement inside the loop checks if the current
number is even. If the current number is an even integer, we apply the
continue statement to skip the current iteration and proceed to the next. We
print the current number if it is odd.

Pass Statement in Python

The pass statement is a placeholder statement that does nothing. It is used


when a statement is required syntactically, but you don’t want to execute
any code. Pass is mostly used as a placeholder for functions or conditional
statements that have not yet been implemented.

Syntax of Pass Statement in Python


The syntax for the pass statement in Python is as follows:

while condition:
# statements before the pass statement

if condition:

pass

# statements after the pass statement

In this syntax, the pass statement is used inside a loop (while loop or for
loop) and inside an if statement. When the pass statement is executed, it
does nothing, and the control is transferred to the next statement after the
loop or the if statement.

Example of Pass Statement in Python


Here’s an example of the pass statement in Python:
x = 25
if x > 15:
pass
else:
print("x is less than or equal to 15")

Python Functions

Python Functions is a block of statements that return the specific task. The idea is to
put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again.

def function_name(parameters):
function body
Example

def hello_world_func():
print("hello world")

A top-to-down approach towards building the processing logic involves


defining blocks of independent reusable functions. A Python function may be
invoked from any other function by passing required data (called parameters
or arguments). The called function returns its result back to the calling
environment.
Python provides the following types of functions −
 Built-in functions
 Functions defined in built-in modules
 User-defined functions

Python's standard library includes number of built-in functions. Some of


Python's built-in functions are print(), int(), len(), sum(), etc. These
functions are always available, as they are loaded into computer's memory
as soon as you start Python interpreter.
The standard library also bundles a number of modules. Each module
defines a group of functions. These functions are not readily available. You
need to import them into the memory from their respective modules.
In addition to the built-in functions and functions in the built-in modules,
you can also create your own functions. These functions are called user-
defined functions.

Defining a Function in Python


You can define custom functions to provide the required functionality. Here
are simple rules to define a function in Python.

Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).

Any input parameters or arguments should be placed within these


parentheses. You can also define parameters inside these parentheses.

The first statement of a function can be an optional statement; the


documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is
indented.

The statement return [expression] exits a function, optionally


passing back an expression to the caller. A return statement with no
arguments is the same as return None.

Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform
them in the same order that they were defined.
Once the function is defined, you can execute it by calling it from another
function or directly from the Python prompt.

Example
The following example shows how to define a function greetings(). The
bracket is empty so there aren't any parameters.
The first line is the docstring. Function block ends with return statement.
when this function is called, Hello world message will be printed.
def greetings():
"This is docstring of greetings function"
print ("Hello World")
return

greetings()

Calling a Function in Python


Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by
calling it from another function or directly from the Python prompt.
Following is the example to call printme() function −
# Function definition is heredef printme( str ):
"This prints a passed string into this function"
print (str)
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following output −
I'm first call to user defined function!
Again second call to the same function

Pass by Reference vs Value


The function calling mechanism of Python differs from that of C and C++.
There are two main function calling mechanisms: Call by Value and Call
by Reference.
When a variable is passed to a function, what does the function do to it? If
any changes to its variable doesnot get reflected in the actual argument, then
it uses call by value mechanism. On the other hand, if the change is
reflected, then it becomes call by reference mechanism.

C/C++ functions are said to be called by value. When a function in C/C+


+ is called, the value of actual arguments is copied to the variables
representing the formal arguments. If the function modifies the value of
formal aergument, it doesn't reflect the variable that was passed to it.
Python uses pass by reference mechanism. As variable in Python is a
label or reference to the object in the memory, the both the variables used as
actual argument as well as formal arguments really refer to the same object
in the memory. We can verify this fact by checking the id() of the passed
variable before and after passing.
def testfunction(arg):
print ("ID inside the function:", id(arg))
var="Hello"print ("ID before passing:", id(var))
testfunction(var)
If the above code is executed, the id() before passing and inside the function
is same.
ID before passing: 1996838294128
ID inside the function: 1996838294128
The behaviour also depends on whether the passed object is mutable or
immutable. Python numeric object is immutable. When a numeric object is
passed, and then the function changes the value of the formal argument, it
actually creates a new object in the memory, leaving the original variable
unchanged.
def testfunction(arg):
print ("ID inside the function:", id(arg))
arg=arg+1
print ("new object after increment", arg, id(arg))

var=10print ("ID before passing:", id(var))


testfunction(var)print ("value after function call", var)
It will produce the following output −
ID before passing: 140719550297160
ID inside the function: 140719550297160
new object after increment 11 140719550297192
value after function call 10
Let us now pass a mutable object (such as a list or dictionary) to a function.
It is also passed by reference, as the id() of lidt before and after passing is
same. However, if we modify the list inside the function, its global
representation also reflects the change.
Here we pass a list, append a new item, and see the contents of original list
object, which we will find has changed.
def testfunction(arg):
print ("Inside function:",arg)
print ("ID inside the function:", id(arg))
arg=arg.append(100)

var=[10, 20, 30, 40]print ("ID before passing:", id(var))


testfunction(var)print ("list after function call", var)
It will produce the following output −
ID before passing: 2716006372544
Inside function: [10, 20, 30, 40]
ID inside the function: 2716006372544
list after function call [10, 20, 30, 40, 100]

Function Arguments
The process of a function often depends on certain data provided to it while
calling it. While defining a function, you must give a list of variables in
which the data passed to it is collected. The variables in the parentheses are
called formal arguments.
When the function is called, value to each of the formal arguments must be
provided. Those are called actual arguments.

Example
Let's modify greetings function and have name an argument. A string passed
to the function as actual argument becomes name variable inside the
function.
def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return

greetings("Samay")
greetings("Pratima")
greetings("Steven")
It will produce the following output −
Hello Samay
Hello Pratima
Hello Steven

Function with Return Value


The return keyword as the last statement in function definition indicates
end of function block, and the program flow goes back to the calling
function. Although reduced indent after the last statement in the block also
implies return but using explicit return is a good practice.
Along with the flow control, the function can also return value of an
expression to the calling function. The value of returned expression can be
stored in a variable for further processing.

Example
Let us define the add() function. It adds the two values passed to it and
returns the addition. The returned value is stored in a variable called result.
def add(x,y):
z=x+y
return z

a=10
b=20
result = add(a,b)print ("a = {} b = {} a+b = {}".format(a, b, result))
It will produce the following output −
a = 10 b = 20 a+b = 30

A variable is only available from inside the region it is created. This is called scope.

Local Scope
A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function.

A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

Function Inside Function


As explained in the example above, the variable x is not available outside the function, but it
is available for any function inside the function:

Example

The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()

Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the
global scope.

Global variables are available from within any scope, global and local.

Example

A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Naming Variables
If you operate with the same variable name inside and outside of a function, Python will treat
them as two separate variables, one available in the global scope (outside the function) and
one available in the local scope (inside the function):

Example
The function will print the local x, and then the code will print the global x:

x = 300

def myfunc():
x = 200
print(x)

myfunc()

print(x)

Python Modules
Python Module is a file that contains built-in functions, classes,its and variables.
There are many Python modules, each with its specific work.

In this article, we will cover all about Python modules, such as How to create our own
simple module, Import Python modules, From statements in Python, we can use the
alias to rename the module, etc.
To create a Python module, write the desired code and save that in a file with .py
extension. Let’s understand it better with an example:

Example:

Let’s create a simple calc.py in which we define two functions, one add and another
subtract.

# A simple module, calc.py


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another module using
the import statement in some other Python source file.

When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.

Note: A search path is a list of directories that the interpreter searches for importing a
module.

For example, to import the module calc.py, we need to put the following command at
the top of the script.

Syntax to Import Module in Python


import module
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is used.

Importing modules in Python Example

Now, we are importing the calc that we created earlier to perform add operation.

# importing module calc.py


import calc

print(calc.add(10, 2))
Output:

12

Python Exception Handling

Python try...except Block


The try...except block is used to handle exceptions in Python. Here's the
syntax of try...except block:

try:

# code that may cause exceptionexcept:

# code to run when exception occurs

Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by an except block.

When an exception occurs, it is caught by the except block. The except block
cannot be used without the try block.

Example: Exception Handling Using try...except


try:

numerator = 10

denominator = 0
result = numerator/denominator

print(result)except:

print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0.

Run Code

In the example, we are trying to divide a number by 0. Here, this code


generates an exception.

To handle the exception, we have put the code, result =

numerator/denominator inside the try block. Now when an exception occurs, the
rest of the code inside the try block is skipped.

The except block catches the exception and statements inside the except block
are executed.

If none of the statements in the try block generates an exception,


the except block is skipped.

Catching Specific Exceptions in Python

For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception differently.

The argument type of each except block indicates the type of exception that
can be handled by it. For example,

try:

even_numbers = [2,4,6,8]

print(even_numbers[5])
except ZeroDivisionError:

print("Denominator cannot be 0.")

except IndexError:

print("Index Out of Bound.")

# Output: Index Out of Bound

Run Code

In this example, we have created a list named even_numbers .

Since the list index starts from 0, the last element of the list is at index 3.
Notice the statement,

print(even_numbers[5])

Here, we are trying to access a value to the index 5.


Hence, IndexError exception occurs.

When the IndexError exception occurs in the try block,

 The ZeroDivisionError exception is skipped.

 The set of code inside the IndexError exception is executed.

Files

A file object is created using open function and here is a list of functions which
can be called on this object −
file.close()
1
Close the file. A closed file cannot be read or written any more.

file.flush()
2 Flush the internal buffer, like stdio's fflush. This may be a no-op on some
file-like objects.

file.fileno()
3 Returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating system.

file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.

file.next()
5
Returns the next line from the file each time it is being called.

file.read([size])
6 Reads at most size bytes from the file (less if the read hits EOF before
obtaining size bytes).

file.readline([size])
7 Reads one entire line from the file. A trailing newline character is kept in
the string.

file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If
8 the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after
rounding up to an internal buffer size) are read.

file.seek(offset[, whence])
9
Sets the file's current position

file.tell()
10
Returns the file's current position
Here is a list of the different modes of opening a file −
Sr.No. Modes & Description

r
1 Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.

2 rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.

r+
3 Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

rb+
4 Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.

w
5 Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.

wb
6 Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.

w+
7 Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.

wb+
Opens a file for both writing and reading in binary format. Overwrites the
8
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.

a
Opens a file for appending. The file pointer is at the end of the file if the file
9
exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.

ab
Opens a file for appending in binary format. The file pointer is at the end of
10
the file if the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.

a+
Opens a file for both appending and reading. The file pointer is at the end of
11
the file if the file exists. The file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.

ab+
Opens a file for both appending and reading in binary format. The file pointer
12
is at the end of the file if the file exists. The file opens in the append mode. If
the file does not exist, it creates a new file for reading and writing.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")print "Name of the file: ", fo.nameprint "Closed or
not : ", fo.closedprint "Opening mode : ", fo.modeprint "Softspace flag : ",
fo.softspace
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0

Networking in Python
What are Sockets?
Consider a bidirectional communication channel, the sockets are the endpoints of this
communication channel. These sockets (endpoints) can communicate within a
process, between processes on the same machine, or between processes on different
machines. Sockets use different protocols for determining the connection type for
port-to-port communication between clients and servers.
Socket Programming
Socket programming is a way of connecting two nodes on a network to communicate
with each other. One socket(node) listens on a particular port at an IP, while the other
socket reaches out to the other to form a connection. The server forms the listener
socket while the client reaches out to the server. They are the real backbones behind
web browsing. In simpler terms, there is a server and a client. We can use the socket
module for socket programming. For this, we have to include the socket module –

import socket
to create a socket we have to use the socket.socket() method.

Syntax:

socket.socket(socket_family, socket_type, protocol=0)


Where,

socket_family: Either AF_UNIX or AF_INET


socket_type: Either SOCK_STREAM or SOCK_DGRAM.
protocol: Usually left out, defaulting to 0.
Example:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)
Output:

<socket.socket fd=74, family=AddressFamily.AF_INET,


type=SocketKind.SOCK_STREAM, proto=0, laddr=(‘0.0.0.0’, 0)>
The socket module provides various methods for both client and server-side
programming. Let’s see each method in detail.

Socket Server Methods


These methods are used on the server-side. Let’s see each method in detail –

Function Name Description


s.bind() Binds address to the socket. The address contains the pair of hostname
and the port number.
s.listen() Starts the TCP listener
s.accept() Passively accepts the TCP client connection and blocks until the
connection arrives
Socket Client Methods
This method is used on the client side. Let’s see this method in detail –

Function Name Description


s.connect() Actively starts the TCP server connection
Socket General Methods
These are the general methods of the socket module. Let’s see each method in detail.

Function Name Description


s.send() Sends the TCP message
s.sendto() Sends the UDP message
s.recv() Receives the TCP message
s.recvfrom() Receives the UDP message
s.close() Close the socket
socket.ghostname() Returns the host name
Simple Server Client Program
Server
A server has a bind() method which binds it to a specific IP and port so that it can
listen to incoming requests on that IP and port. A server has a listen() method which
puts the server into listening mode. This allows the server to listen to incoming
connections. And last a server has an accept() and close() method. The accept method
initiates a connection with the client and the close method closes the connection with
the client.
3.2 Introduction to Raspberry 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 purposeI/O pins. Since Raspberry Pi runs Linux perating
system, it supports Python "out of the box".
OS for Raspberry Pi

Raspberry Pi Foundation officially provides Debian based Raspbian OS. Also, they
provide NOOBS OS for Raspberry Pi. We can install several Third-Party versions of
OS like Ubuntu, Archlinux, RISC OS, Windows 10 IOT Core, etc.
Raspbian OS is official Operating System available for free to use. This OS is
efficiently optimized to use with Raspberry Pi. Raspbian have GUI which includes
tools for Browsing, Python programming, office, games, etc.

We should use SD card (minimum 8 GB recommended) to store the OS (operating


System).

Raspberry Pi is more than computer as it provides access to the on-chip hardware i.e.
GPIOs for developing an application. By accessing GPIO, we can connect devices
like LED, motors, sensors, etc and can control them too.

Raspberry Pi processor

It has ARM based Broadcom Processor SoC along with on-chip GPU (Graphics
Processing Unit).

The CPU speed of Raspberry Pi varies from 700 MHz to 1.2 GHz. Also, it has on-
board SDRAM that ranges from 256 MB to 1 GB.

Raspberry Pi also provides on-chip SPI, I2C, I2S and UART modules.

Versions of Raspberry pi models


There are different versions of raspberry pi available as listed below:

1. Raspberry Pi 1 Model A
2. Raspberry Pi 1 Model A+
3. Raspberry Pi 1 Model B
4. Raspberry Pi 1 Model B+
5. Raspberry Pi 2 Model B
6. Raspberry Pi 3 Model B
7. Raspberry Pi Zero

Out of the above versions of Raspberry Pi, more prominently use Raspberry Pi and
their features are as follows:

Raspberry Pi 2 Raspberry Pi 3
Raspberry Pi Raspberry Pi
Features
Model B+ Model B Model B zero

SoC BCM2835 BCM2836 BCM2837 BCM2835


CPU ARM11 Quad Cortex A7 Quad Cortex A53 ARM11

Operating
700 MHz 900 MHz 1.2 GHz 1 GHz
Freq.

RAM 512 MB SDRAM 1 GB SDRAM 1 GB SDRAM 512 MB SDRAM

250 MHz Videocore 250MHz 400 MHz 250MHz


GPU
IV Videocore IV Videocore IV Videocore IV

Storage micro-SD Micro-SD micro-SD micro-SD

Ethernet Yes Yes Yes No

Wireless WiFi and Bluetooth No No No

Raspberry Pi zero Board

Raspberry Pi Zero
Raspberry Pi Board

Raspberry Pi 3 Hardware Details


The On-chip hardware of Raspberry Pi 3 (here) is as shown in below figure,
Raspberry Pi 3 Model B Hardware

Some Hardware Components shown above are mention below:

1. HDMI (High-Definition Multimedia Interface): It is used for transmitting


uncompressed video or digital audio data to the Computer Monitor, Digital
TV, etc. Generally, this HDMI port helps to connect Raspberry Pi to the
Digital television.
2. CSI Camera Interface: CSI (Camera Serial Interface) interface provides a
connection in between Broadcom Processor and Pi camera. This interface
provides electrical connections between two devices.
3. DSI Display Interface: DSI (Display Serial Interface) Display Interface is
used for connecting LCD to the Raspberry Pi using 15-pin ribbon cable. DSI
provides fast High-resolution display interface specifically used for sending
video data directly from GPU to the LCD display.
4. Composite Video and Audio Output: The composite Video and Audio
output port carries video along with audio signal to the Audio/Video systems.
5. Power LED: It is a RED colored LED which is used for Power indication.
This LED will turn ON when Power is connected to the Raspberry Pi. It is
connected to 5V directly and will start blinking whenever the supply voltage
drops below 4.63V.
6. ACT PWR: ACT PWR is Green LED which shows the SD card activity.
Raspbian OS Install
Raspberry Pi operating systems are available as a disk image, either ISO
or IMG format. Writing the file is straightforward. Several tools are
available that can write a Raspberry Pi operating system to an SD card.
The best options are:
 Raspberry Pi Imager
 Etcher
 Command Line (Linux and macOS)

Available from the official Raspberry Pi website, Raspberry Pi Imager is a utility that
writes an operating system to your Pi's SD card. A list of operating systems is
included in the app, such as Raspberry Pi OS and other desktops, media players, and
emulation and gaming OSs.

Download: Raspberry Pi Imager

Raspberry Pi Imager is available for Windows, macOS, and Ubuntu. Once installed
on your computer, the process is simple:

1. Under Operating System click Choose OS


2. Browse the list for your preferred OSs and select the one you want
3. Click Ctrl+Shift+X to preconfigure advanced options (see below)
4. Next, click Choose Storage to select the SD card
5. Click Write
Wait while the data is written and verified. When done, click Continue, then close the
imager tool.
The Raspberry Pi Imager features some handy time saving advanced options. These
can be preconfigured to save you messing around after booting the Pi for the first
time.
For example, you can set a hostname for the device and enable SSH, complete with
user credentials. Wi-Fi - with details copied from your the PC running Raspberry Pi
Imager - can also be configured in advance.

To use Etcher, you'll need to download the chosen operating system image to your PC
in advance. This provides you with the flexibility to install any suitable OS without
being restricted to a curated list. (While Raspberry Pi Imager permits the use of a
downloaded image file, it is not the default option.)

Once you've downloaded your preferred disk image, download Etcher. This is a tool
for writing disk images from your computer to flash storage, whether an SD card or a
USB thumb drive. It's a simple mouse-driven app, available for Windows, Linux, and
macOS.

Download: Etcher (Free)

With Etcher installed and running, you'll notice three buttons: Select Image, Select
Drive, and Flash. To flash an image with Etcher:

1. Click Select Image


2. Browse to the downloaded ISO or IMG file
3. Next, click Select Drive
4. Confirm the correct SD card is selected
5. Finally, click Flash to begin writing the data
6. If you prefer to set up your Raspberry Pi's SD card in the command line, this is
straightforward in Linux. Before proceeding, ensure you have downloaded the
appropriate ISO disk image of the operating system you plan to use.
7. This method uses the dd command, which should be used with care. Confirm
you've entered the command correctly before proceeding, as misuse of dd can be
destructive.
8. Start by inserting the SD card in the reader, then search for it in the /dev directory
with
9. sudo ls -ltr /dev/*
10. You should spot the SD card as mmcblk0. Watch out for reference to the
partitions on the card (mmcblk0p1, mmcblk0p2, etc.) which you should ignore. The
entire disk – mmcblk0 – is used for this method.
11. When you're ready, enter the command:
12. sudo dd bs=1M if=/path/to/raspberrypi/image of=/dev/sdcardname
status=progress conv=fsync
13. The if= section of the command is the file path to the ISO file; the of= portion is
the destination. Be sure to edit the command above to reflect your system.
14. When you hit Enter, the command will run. This isn't a quick process, so take the
opportunity to enjoy a hot drink while it completes.
15. Other Tools for Installing Raspberry Pi Operating Systems
16. Some other, slightly more complicated tools are available for installing an OS on
your Raspberry Pi's SD card.

3.3 Interfacing Raspberry Pi with basic peripherals


Raspberry pi has Serial, SPI and I2C interfaces for data transfer.

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. in an SPI connection, there are
five pins on Raspberry Pi for SPI interface :

MISO (Master in slave out) – Master line for sending data to the peripherals.
MOSI (Master out slave in) – Slave line for sending data to the master.
SCK (Serial Clock) – Clock generated by master to synchronize data transmission
CE0 (Chip Enable 0) – To enable or disable devices
CE0 (Chip Enable 1) – To enable or disable 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) an
SCL (Clock Line).

3.4 Implementation of IoT with Raspberry Pi


Blinking of LED
In order to blink the LED, we need to access the GPIO (General Purpose
Input/Output) Pins of the Raspberry Pi.
while True: # Run forever
GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(8, GPIO.LOW) # Turn off
sleep(1)

LDR with Raspberry Pi

In the world of electrical engineering, there are two type of input and output (I/O):
analogue and digital. Digital I/O is fairly easy to understand; it’s
either on or off, 1 or 0.

When talking about voltages and the Raspberry Pi, any input that is approximately
below 1.8V is considered off and anything above 1.8V is considered on. For output,
0V is off and 3.3V is on.

Analogue I/O is a little trickier. With an analogue input, we can have a range of
voltages from 0V up to 3.3V, and the Raspberry Pi is unable to detect exactly what
that voltage is.
How, then, can we use a Raspberry Pi to determine the value of an analogue input, if
it can only tell when the voltage to a GPIO pin goes above 1.8V?

When current is fed into a capacitor, it will begin to store charge. The voltage across
the capacitor will start off low, and increase as the charge builds up.

By putting a resistor in series with the capacitor, you can slow the speed at which it
charges. With a high resistance, the capacitor will charge slowly, whereas a low
resistance will let it charge quickly.

If you time how long it takes the capacitor’s voltage to get over 1.8V (or be on), you
can work out the resistance of the component in series with it.

Luckily, most of the complicated code you would have to write to detect the light
levels received by the LDR has been abstracted away by the gpiozero library. This
library will handle the timing of the capacitor’s charging and discharging for you.

Use the following code to set up the light sensor:

from gpiozero import LightSensor, Buzzer

ldr = LightSensor(4) # alter if using a different pinwhile True:


print(ldr.value)
Run this code, then cover the LDR with your hand and watch the value change. Try
shining a strong light onto the LDR.

Many, but not all, capacitors are polarised which means they have a positive and a
negative leg. In this case, the negative leg is shorter and should be marked with a ‘-‘
symbol.
Light-dependent resistors

An LDR (sometimes called a photocell) is a special type of resistor.

When light hits the LDR, its resistance is very low, but when it’s in the dark its
resistance is very high.

By placing a capacitor in series with an LDR, the capacitor will charge at different
speeds depending on whether it’s light or dark.

Creating a light-sensing circuit

o Place an LDR into your breadboard, as shown below:


o
Luckily, most of the complicated code you would have to write to detect the light
levels received by the LDR has been abstracted away by the gpiozero library. This
library will handle the timing of the capacitor’s charging and discharging for you.

Use the following code to set up the light sensor:

from gpiozero import LightSensor, Buzzer

ldr = LightSensor(4) # alter if using a different


pinwhile True:
print(ldr.value)
Run this code, then cover the LDR with your hand and watch the value change. Try
shining a strong light onto the LDR.

You might also like