0% found this document useful (0 votes)
27 views27 pages

Iot Unit - III Notes

This document provides an overview of Python programming, including its history, features, and applications in various fields such as web development, data science, and IoT. It covers key concepts like data structures, conditional statements, and loops, along with examples to illustrate their usage. Additionally, it compares Python with Java and discusses the reasons to learn Python, its limitations, and its extensive library support.

Uploaded by

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

Iot Unit - III Notes

This document provides an overview of Python programming, including its history, features, and applications in various fields such as web development, data science, and IoT. It covers key concepts like data structures, conditional statements, and loops, along with examples to illustrate their usage. Additionally, it compares Python with Java and discusses the reasons to learn Python, its limitations, and its extensive library support.

Uploaded by

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

Internet of Things II – I JNTUH-R22

UNIT – 3: PYTHON PROGRAMMING


Topics:

☞ Introduction to Python programming


☞ Introduction to Raspberry Pi
☞ Interfacing Raspberry Pi with basic peripherals
☞ Implementation of IoT with Raspberry Pi
☞ Case studies.
3.1. INTRODUCTION TO PYTHON PROGRAMMING:

What is Python?

Python is a widely used high-level, interpreted, and popular programming language. It


was created by Guido van Rossum in 1991 and further developed by the Python Software
Foundation. It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code. Python is a programming
language that lets you work quickly and integrate systems more efficiently.

History of Python

Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a
Dutch programmer, began working on Python while at the Centrum Wiskunde & Informatica
(CWI) in the Netherlands. He wanted to create a successor to the ABC programming
language that would be easy to read and efficient.

In February 1991, the first public version of Python, version 0.9.0, was
released. This marked the official birth of Python as an open-source project. The language
was named after the British comedy series "Monty Python's Flying Circus".

VMTW Page | 1
Internet of Things II – I JNTUH-R22

Python development has gone through several stages. In January 1994, Python 1.0 was
released as a usable and stable programming language. This version included many of the
features that are still present in Python today.

From the 1990s to the 2000s, Python gained popularity for its simplicity, readability,
and versatility. In October 2000, Python 2.0 was released. Python 2.0 introduced list
comprehensions, garbage collection, and support for Unicode.

In December 2008, Python 3.0 was released. Python 3.0 introduced several backward-
incompatible changes to improve code readability and maintainability.

Throughout 2010s, Python's popularity increased, particularly in fields like data


science, machine learning, and web development. Its rich ecosystem of libraries and frameworks
made it a favourite among developers.

The Python Software Foundation (PSF) was established in 2001 to promote, protect,
and advance the Python programming language and its community.

Python is widely used language


Python is used for:
✍ Web Development: Frameworks like Django, Flask.
✍ Data Science and Analysis: Libraries like Pandas, NumPy, Matplotlib.
✍ Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.
✍ Automation and Scripting: Automate repetitive tasks.
✍ Game Development: Libraries like Pygame.
✍ Web Scraping: Tools like BeautifulSoup, Scrapy.
✍ Desktop Applications: GUI frameworks like Tkinter, PyQt.
✍ Scientific Computing: SciPy, SymPy.
✍ Internet of Things (IoT): MicroPython, Raspberry Pi.
✍ DevOps and Cloud: Automation scripts and APIs.
✍ Cybersecurity: Penetration testing and ethical hacking tools.

VMTW Page | 2
Internet of Things II – I JNTUH-R22

Key Features of Python:

 Python is Easy to Learn and Use: There is no prerequisite to start Python, since it is
Ideal programming language for beginners.

 High Level Language: Python don’t let you worry about low-level details, like
memory management, hardware-level operations etc.

 Python is Interpreted: Code is executed line-by-line directly by interpreter, and no


need for separate compilation. Which means – You can run the same code across
different platforms. -You can make the changes in code without restarting the program.

 Dynamic Typed: Python is a dynamic language, meaning there are no need to


explicitly declare the data type of a variable. Type is checked during runtime, not at
compile time.

 Object Oriented: Python supports object-oriented concepts like classes, inheritance,


and polymorphism etc. OOPs empowers Python with modularity, reusability and easy
to maintain code.

 Extensive Library is Available: Python has huge set of library and modules, which
can make development lot easier and faster.

 Open-Source with Huge community Support: Along with opensource, Python is


blessed with very large community contributing to its further development.

 Cross Platform: Same Python code can run on Windows, macOS and Linux, without
any modification in code.

 Good Career Opportunities: Python is in high demand across industries like Software
development, AI, finance, and cloud computing etc.

What can you do with Python?


 Python can be used to develop full-stack web applications and RESTful APIs.
 Python can be used to create AI models and machine learning applications.

VMTW Page | 3
Internet of Things II – I JNTUH-R22

 Python can be used for financial modeling and algorithmic trading.


 Python can build chatbot and voice assistant applications with NLP.
 Python can be used for blockchain development and cryptocurrency platforms. And
Much More..

Why Learn Python?


Whether you are a beginner or an experienced developer, both have their own benefits.
For Beginners:
☞ Easy Syntax: Python syntax is like plain English, which allows you to focus on logic

instead of worrying about complex rules.


☞ Built-in Libraries for Beginners: Python has beginner friendly libraries like random,

re, os etc, which can be used while learning fundamentals.


☞ Error Friendly: Python’s error messages are easy to understand and debug.

☞ Project Oriented Learning: You can start making simple projects while learning

the Python basics.

For Experienced:
☞ Easy Career Transition: If you know any other programming language, moving to

Python is super easy.


☞ Great for Upskilling: Moving to Python expends your skill sets and gives opportunity

to work in areas like AI, Data Science, web development etc.


☞ High Demand of Python in Emerging tech: Python is widely used in trending

domains, like Data Science, Machine Learning, Cloud Computing etc.


☞ Bridge between Roles: For software developers working with different language,

learning Python can help you integrate advanced features like AI in your projects.

Limitation of Python:
 Performance Limitations: Python is an interpreted language which makes it slower
than compiled languages like C++ or Java.
 Not preferred for Mobile Apps and Front End: Python isn’t preferred for Front End
dev or mobile apps because of slower execution speeds and limited frameworks
compared to JavaScript or Swift.

VMTW Page | 4
Internet of Things II – I JNTUH-R22

 Memory Expensive: Python consumes more memory because of its high-level nature
and dynamic typing.
 Lack of Strong Typing: Dynamic typing makes Python easy to code, but it can lead to
runtime errors that would be caught at compile time in statically typed languages like
Java or C#.
 Not Suitable for Game development: Python lacks the high speed and low-level
hardware control needed for game engines.

Java vs. Python

Python is an excellent choice for rapid development and scripting tasks. Whereas Java
emphasizes a strong type system and object-oriented programming.

Here are some basic programs that illustrates key differences between them.

Printing 'Hello World'

Python Code:

print("Hello World!")
Output:

Hello, World!

In Python, it is one line of code. It requires simple syntax to print 'Hello World'

Java Code:

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

VMTW Page | 5
Internet of Things II – I JNTUH-R22

Output:

Hello, World!

In Java, we need to declare classes, method structures many other things.

While both programs give the same output, we can notice the syntax difference in the print
statement.

o In Python, it is easy to learn and write code. While in Java, it requires more code to
perform certain tasks.
o Python is dynamically typed, meaning we do not need to declare the variable Whereas
Java is statistically typed, meaning we need to declare the variable type.
o Python is suitable for various domains such as Data Science, Machine Learning, Web
development, and more. Whereas Java is suitable for web development, mobile app
development (Android), and more.

Python print() Function

Python print() function is used to display output to the console or terminal. It allows us to
display text, variables and other data in a human readable format.

Syntax:

print(object(s), sep=separator, end=end, file=file, flush=flush)

It takes one or more arguments separated by comma(,) and adds a 'newline' at the end by
default.

Parameters:

o object(s) - As many as you want data to display, will first converted into string and
printed to the console.
o sep - Separates the objects by a separator passed, default value = " ".

VMTW Page | 6
Internet of Things II – I JNTUH-R22

o end - Ends a line with a newline character


o file - a file object with write method, default value = sys.stdout

Example:

# Displaying a string
print("Hello, World!")

# Displaying multiple values


name = "Aman"
age = 21
print("Name:", name, "Age:", age)

# Printing variables and literals


x=5
y=7
print("x =", x, "y =", y, "Sum =", x + y)

# Printing with formatting


percentage = 85.75
print("Score: {:.2f}%".format(percentage))
Output:

Hello, World!
Name: Aman Age: 21
X = 5 y = 7 Sum = 12
Score: 85.75%

In this example, the print statement is used to print string, integer, and float values in a human
readable format.

The print statement can be used for debugging, logging and to provide information to the user.

VMTW Page | 7
Internet of Things II – I JNTUH-R22

Python Conditional Statements

Conditional statements help us to execute a particular block for a particular condition. In


this tutorial, we will learn how to use conditional expression to execute a different block of
statements. Python provides if and else keywords to set up logical conditions. The elif keyword
is also used as a conditional statement.

Example code for if..else statement

x = 10
y=5

if x > y:
print("x is greater than y")
else:
print("y is greater than or equal to x")
Output:

x is greater than y

In the above code, we have two variables, x, and y, with 10 and 5, respectively. Then we
used an if..else statement to check if x is greater than y or vice versa. If the first condition is true,
the statement "x is greater than y" is printed. If the first condition is false, the statement "y is
greater than or equal to x" is printed instead.

The if keyword checks the condition is true and executes the code block inside it. The
code inside the else block is executed if the condition is false. This way, the if..else statement
helps us to execute different blocks of code based on a condition.

We will learn about this in more detail in the further article for the Python tutorial.

VMTW Page | 8
Internet of Things II – I JNTUH-R22

Python Loops

Sometimes we may need to alter the flow of the program. The execution of a specific
code may need to be repeated several times. For this purpose, the programming languages
provide various loops capable of repeating some specific code several times. Consider the
following tutorial to understand the statements in detail.

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x, end=" ")
Output:

apple banana cherry

Python While Loop

i=1
while i<5:
print(i, end=" ")
i += 1
Output:

1234

In the above example code, we have demonstrated using two types of loops in Python -
For loop and While loop.

The For loop is used to iterate over a sequence of items, such as a list, tuple, or string. In
the example, we defined a list of fruits and used a for loop to print each fruit, but it can also be
used to print a range of numbers.

VMTW Page | 9
Internet of Things II – I JNTUH-R22

The While loop repeats a code block if the specified condition is true. In the example, we
have initialized a variable i to 1 and used a while loop to print the value of i until it becomes
greater than or equal to 6. The i += 1 statement is used to increment the value of i in each
iteration.

We will learn about them in the tutorial in detail.

Python Data Structures

Python offers four built-in data structures: lists, tuples, sets, and dictionaries that
allow us to store data in an efficient way. Below are the commonly used data structures in
Python, along with example code:

1. Lists

o Lists are ordered collections of data elements of different data types.


o Lists are mutable meaning a list can be modified anytime.
o Elements can be accessed using indices.
o They are defined using square bracket '[]'.

Example:

# Create a list
fruits = ['apple', 'banana', 'cherry']
print("fuirts[1] =", fruits[1])

# Modify list
fruits.append('orange')
print("fruits =", fruits)

num_list = [1, 2, 3, 4, 5]
# Calculate sum
sum_nums = sum(num_list)
print("sum_nums =", sum_nums)

VMTW Page | 10
Internet of Things II – I JNTUH-R22

Output:

fuirts[1] = banana
fruits = ['apple', 'banana', 'cherry', 'orange']
sum_nums = 15

2. Tuples

o Tuples are also ordered collections of data elements of different data types, similar to
Lists.
o Elements can be accessed using indices.
o Tuples are immutable meaning Tuples can't be modified once created.
o They are defined using open bracket '()'.

Example:

# Create a tuple
point = (3, 4)
x, y = point
print("(x, y) =", x, y)

# Create another tuple


tuple_ = ('apple', 'banana', 'cherry', 'orange')
print("Tuple =", tuple_)
Output:

(x, y) = 3 4
Tuple = ('apple', 'banana', 'cherry', 'orange')

VMTW Page | 11
Internet of Things II – I JNTUH-R22

3. Sets

o Sets are unordered collections of immutable data elements of different data types.
o Sets are mutable.
o Elements can't be accessed using indices.
o Sets do not contain duplicate elements.
o They are defined using curly braces '{}'

Example:

# Create a set
set1 = {1, 2, 2, 1, 3, 4}
print("set1 =", set1)

# Create another set


set2 = {'apple', 'banana', 'cherry', 'apple', 'orange'}
print("set2 =", set2)
Output:

set1 = {1, 2, 3, 4}
set2 = {'apple', 'cherry', 'orange', 'banana'}

4. Dictionaries

o Dictionaries are key-value pairs that allow you to associate values with unique keys.
o They are defined using curly braces '{}' with key-value pairs separated by colons ':'.
o Dictionaries are mutable.
o Elements can be accessed using keys.

Example:

# Create a dictionary
person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'}

VMTW Page | 12
Internet of Things II – I JNTUH-R22

print("person =", person)


print(person['name'])

# Modify Dictionary
person['age'] = 27
print("person =", person)

Output:

person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'}


Umesh
person = {'name': 'Umesh', 'age': 27, 'city': 'Noida'}

These are just a few examples of Python's built-in data structures. Each data structure has
its own characteristics and use cases.

Python Functional Programming

This section of the Python tutorial defines some important tools related to functional
programming, such as lambda and recursive functions. These functions are very efficient in
accomplishing complex tasks. We define a few important functions, such as reduce, map, and
filter. Python provides the functools module that includes various functional programming tools.
Visit the following tutorial to learn more about functional programming.

Recent versions of Python have introduced features that make functional programming
more concise and expressive. For example, the "walrus operator":= allows for inline variable
assignment in expressions, which can be useful when working with nested function calls or list
comprehensions.

VMTW Page | 13
Internet of Things II – I JNTUH-R22

Python Function:

1. Lambda Function - A lambda function is a small, anonymous function that can take
any number of arguments but can only have one expression. Lambda functions are often
used in functional programming to create functions "on the fly" without defining a named
function.
2. Recursive Function - A recursive function is a function that calls itself to solve a
problem. Recursive functions are often used in functional programming to perform
complex computations or to traverse complex data structures.
3. Map Function - The map() function applies a given function to each item of an iterable
and returns a new iterable with the results. The input iterable can be a list, tuple, or other.
4. Filter Function - The filter() function returns an iterator from an iterable for which the
function passed as the first argument returns True. It filters out the items from an iterable
that do not meet the given condition.
5. Reduce Function - The reduce() function applies a function of two arguments
cumulatively to the items of an iterable from left to right to reduce it to a single value.
6. functools Module - The functools module in Python provides higher-order functions that
operate on other functions, such as partial() and reduce().
7. Currying Function - A currying function is a function that takes multiple arguments and
returns a sequence of functions that each take a single argument.
8. Memoization Function - Memoization is a technique used in functional programming to
cache the results of expensive function calls and return the cached Result when the same
inputs occur again.
9. Threading Function - Threading is a technique used in functional programming to run
multiple tasks simultaneously to make the code more efficient and faster.

Python Modules:

Python modules are the program files that contain Python code or functions. Python has
two types of modules - User-defined modules and built-in modules. A module the user defines,
or our Python code saved with .py extension, is treated as a user-define module.

VMTW Page | 14
Internet of Things II – I JNTUH-R22

Built-in modules are predefined modules of Python. To use the functionality of the
modules, we need to import them into our current working program.

Python modules are essential to the language's ecosystem since they offer reusable code
and functionality that can be imported into any Python program. Here are a few examples of
several Python modules, along with a brief description of each:

Math: Gives users access to mathematical constants and pi and trigonometric functions.

Datetime: Provides classes for a simpler way of manipulating dates, times, and periods.

OS: Enables interaction with the base operating system, including administration of processes
and file system activities.

Random: The random function offers tools for generating random integers and picking random
items from a list.

JSON: JSON is a data structure that can be encoded and decoded and is frequently used in
online APIs and data exchange. This module allows dealing with JSON.
Re: Supports regular expressions, a potent text-search and text-manipulation tool.

Collections: Provides alternative data structures such as sorted dictionaries, default dictionaries,
and named tuples.

NumPy: NumPy is a core toolkit for scientific computing that supports numerical operations on
arrays and matrices.

Pandas: It provides high-level data structures and operations for dealing with time series and
other structured data types.

Requests: Offers a simple user interface for web APIs and performs HTTP requests.

VMTW Page | 15
Internet of Things II – I JNTUH-R22

Python File I/O

Files are used to store data in a computer disk. In this tutorial, we explain the built-in file
object of Python. We can open a file using Python script and perform various operations such as
writing, reading, and appending. There are various ways of opening a file. We are explained with
the relevant example. We will also learn to perform read/write operations on binary files.

Python's file input/output (I/O) system offers programs to communicate with files stored on a
disc. Python's built-in methods for the file object let us carry out actions like reading, writing,
and adding data to files.

The open() method in Python makes a file object when working with files. The name of the file
to be opened and the mode in which the file is to be opened are the two parameters required by
this function. The mode can be used according to work that needs to be done with the file, such
as "r" for reading, "w" for writing, or "a" for attaching.

After successfully creating an object, different methods can be used according to our
work. If we want to write in the file, we can use the write() functions, and if you want to read and
write both, then we can use the append() function and, in cases where we only want to read the
content of the file we can use read() function. Binary files containing data in a binary rather than
a text format may also be worked with using Python. Binary files are written in a manner that
humans cannot directly understand. The rb and wb modes can read and write binary data in
binary files.

Python Exceptions

An exception can be defined as an unusual condition in a program resulting in an


interruption in the flow of the program.

Whenever an exception occurs, the program stops the execution, and thus the other code
is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python
script. An exception is a Python object that represents an error.

VMTW Page | 16
Internet of Things II – I JNTUH-R22

Python Exceptions are an important aspect of error handling in Python programming. When a
program encounters an unexpected situation or error, it may raise an exception, which can
interrupt the normal flow of the program.

In Python, exceptions are represented as objects containing information about the error,
including its type and message. The most common type of Exception in Python is the Exception
class, a base class for all other built-in exceptions.

To handle exceptions in Python, we use the try and except statements. The try statement is used
to enclose the code that may raise an exception, while the except statement is used to define a
block of code that should be executed when an exception occurs.

For example, consider the following code:

try:
x = int ( input ("Enter a number: "))
y = 10 / x
print ("Result:", y)
except ZeroDivisionError:
print ("Error: Division by zero")
except ValueError:
print ("Error: Invalid input")
Output:

Enter a number: 0
Error: Division by zero

In this code, we use the try statement to attempt to perform a division operation. If either
of these operations raises an exception, the matching except block is executed.

VMTW Page | 17
Internet of Things II – I JNTUH-R22

Python also provides many built-in exceptions that can be raised in similar situations.
Some common built-in exceptions include IndexError, TypeError, and NameError. Also, we
can define our custom exceptions by creating a new class that inherits from the Exception class.

3.2. INTRODUCTION TO RASPBERRY PI:

INTRODUCTION:

The Raspberry Pi is a credit card-sized computer with an ARM processor that can run
Linux. This item is the Raspberry Pi 3 Model B+, which has 1 GB of RAM, dual-band Wi-Fi,
Bluetooth 4.2, Bluetooth Low Energy (BLE), an Ethernet port, HDMI output, audio output, RCA
composite video output (through the 3.5 mm jack), four USB ports, and 0.1″-spaced pins that
provide access to general purpose inputs and outputs (GPIO). The Raspberry Pi requires a
microSD card with an operating system on it (not included).

Fig. Raspberry Pi 3B+ Model Board

Overview:

The Raspberry Pi is a credit card-sized computer. The Raspberry Pi 3 Model B+ is an


improved version of the Raspberry Pi 3 Model B. It is based on the BCM2837B0 system-on-chip
(SoC), which includes a 1.4 GHz quad-core ARMv8 64bit processor and a powerful VideoCore
IV GPU. The Raspberry Pi can run a full range of ARM GNU/Linux distributions, including
Snappy Ubuntu Core, Raspbian, Fedora, and Arch Linux, as well as Microsoft Windows 10 IoT
Core.

VMTW Page | 18
Internet of Things II – I JNTUH-R22

The Raspberry Pi 3 Model B+ has many performance improvements over the Model
B including a faster CPU clock speed (1.4 GHz vs 1.2 GHz), increased Ethernet throughput, and
dual-band WiFi. It also supports Power over Ethernet with a Power over Ethernet HAT (not
included). The MagPi Magazine has a blog post with performance benchmarks comparing various
Raspberry Pi models.

The dual-band wireless LAN comes with modular compliance certification, allowing the
board to be designed into end products with significantly reduced wireless LAN compliance
testing, improving both cost and time to market.

The Raspberry Pi was designed by the Raspberry Pi Foundation to provide an affordable


platform for experimentation and education in computer programming. The Raspberry Pi can be
used for many of the things that a normal desktop PC does, including word-processing,
spreadsheets, high-definition video, games, and programming. USB devices such as keyboards
and mice can be connected via the board’s four USB ports.

Features:

 1.4 GHz quad-core BCM2837B0 ARMv8 64bit CPU

VMTW Page | 19
Internet of Things II – I JNTUH-R22

 1 GB RAM

 VideoCore IV 3D graphics core

 Ethernet port

 dual-band (2.4 GHz and 5 GHz) IEEE 802.11.b/g/n/ac wireless LAN (WiFi)

 Bluetooth 4.2

 Bluetooth Low Energy (BLE)

 Four USB ports

 Full-size HDMI output

 Four-pole 3.5 mm jack with audio output and composite video output

 40-pin GPIO header with 0.1″-spaced male pins those are compatible with our 2×20
stackable female headers and the female ends of our premium jumper wires.
 Camera interface (CSI)

 Display interface (DSI)

 Micro SD card slot

RASPBERRY PI 3B+ MODEL BOARD:

VMTW Page | 20
Internet of Things II – I JNTUH-R22

The Raspberry Pi 3 Tutorial - A Beginner’s Guide:

The Raspberry Pi has a number of ports which you will use to control the Raspberry Pi, and it
can use to control other devices. Your Raspberry Pi will have the following ports:
 USB – USB ports are used to connect a wide variety of components, most commonly a
mouse and keyboard.
 HDMI – The HDMI port outputs video and audio to your monitor.
 Audio – The audio jack allows you to connect standard headphones and speakers.
 Micro USB – The Micro USB port is only for power, do not connect anything else to this
port. Always connect the power after you have already connected everything else.
 GPIO – The GPIO ports allow the Raspberry Pi to control and take input from any
electronic component.
 SD card slot – The Raspberry Pi uses SD cards the same way a full-size computer uses a
hard drive. The SD card provides the Raspberry Pi with internal memory, and stores the
hard drive.

VMTW Page | 21
Internet of Things II – I JNTUH-R22

RASPBERRY PI PINOUT:

VMTW Page | 22
Internet of Things II – I JNTUH-R22

The following table shows the Raspberry Pi pinout, it shows all GPIOs, their
corresponding physical pin numbers, their Broadcom numbering, and corresponding features.

VMTW Page | 23
Internet of Things II – I JNTUH-R22

Function Name Pin no. Pin no. Name Function

DC power 3.3 V 1 2 5V DC power

I2C (SDA) GPIO 2 3 4 5V DC power

I2C (SCL) GPIO 3 5 6 GND

GPCLK0 GPIO 4 7 8 GPIO 14 UART (TXD0)

GND 9 10 GPIO 15 UART (RXD0)

GPIO 17 11 12 GPIO 18 PCM CLK (I2S)

GPIO 27 13 14 GND

GPIO 22 15 16 GPIO 23

DC power 3.3 V 17 18 GPIO 24

SPI (MOSI) GPIO 10 19 20 GND

SPI (MISO) GPIO 9 21 22 GPIO 25

SPI (CLK) GPIO 11 23 24 GPIO 8 SPI (CE0)

GND 25 26 GPIO 7 SPI (CE1)

I2C EEPROM GPIO 0 27 28 GPIO 1 I2C EEPROM

GPIO 5 29 30 GND

GPIO 6 31 32 GPIO 12 PWM0

PWM1 GPIO 13 33 34 GND

PCM FS (I2S) GPIO 19 35 36 GPIO 16

GPIO 26 37 38 GPIO 20 PCM DIN (I2S)

GND 39 40 GPIO 21 PCM Dout (I2S)

VMTW Page | 24
Internet of Things II – I JNTUH-R22

Raspberry Pi Power Pins

The Raspberry Pi comes with two 3.3V pins (pins number 1 and 17) and two 5V pins (pins 2 and
4).
Additionally, there are eight GND pins (pins number: 6, 9, 14, 20, 25, 30, 34, and 39).

Raspberry Pi Digital Inputs and Outputs

Out of the 40 Raspberry Pi GPIOs, 11 are power or GND pins. Besides that, there are two
reserved pins (pins 27 and 28) for I2C communication with an EEPROM (learn more about this).
So, this left us with 16 GPIOs that you can use to connect peripherals. These GPIOs can be used
either as inputs or outputs. Additionally, some of them support specific communication
protocols.

Raspberry Pi I2C Pins

I²C means Inter-Integrated Circuit, and it is a synchronous, multi-master, multi-slave


communication protocol. It allows you to establish communication with other microcontroller
devices, sensors, or displays, for example. You can connect multiple I2C devices to the same
pins as long they have a unique I2C address.

The Raspberry Pi I2C pins are GPIO 2 and GPIO 3:


 SDA: GPIO 2
 SCL: GPIO 3

Raspberry Pi SPI Pins

SPI stands for Serial Peripheral Interface, and it is a synchronous serial data protocol used by
microcontrollers to communicate with one or more peripherals. This communication protocol
allows you to connect multiple peripherals to the same bus interface, as long as each is connected
to a different chip select pin.

VMTW Page | 25
Internet of Things II – I JNTUH-R22

For example, your Raspberry Pi board can communicate with a sensor that supports SPI, another
Raspberry Pi, or a different microcontroller board. These are the Raspberry Pi SPI pins:

 MOSI: GPIO 10
 MISO: GPIO 9
 CLOCK: GPIO 11
 CE0 (chip select): GPIO 8
 CE1 (chip select): GPIO 7

Raspberry Pi Serial (UART) Pins

The UART pins can be used for Serial communication. The Raspberry Pi Serial (UART) pins
are:

 TX: GPIO 14
 RX: GPIO 15

Raspberry Pi PWM Pins

PWM stands for Pulse Width Modulation and it is used to control motors, define varying levels
of LED brightness, define the color of RGB LEDs, and much more.

The Raspberry Pi has 4 hardware PWM pins: GPIO 12, GPIO 13, GPIO 18, GPIO 19.
You can have software PWM on all pins.

Raspberry Pi One-Wire Pins

The Raspberry Pi supports one-wire on all GPIOs, but the default is GPIO4.

VMTW Page | 26
Internet of Things II – I JNTUH-R22

Raspberry Pi PCM Pins

The Raspberry Pi comes with PCM (pulse-code Modulation) pins for digital audio output. These
are the PCM pins:

 Din: GPIO 20
 Dout: GPIO 21
 FS: GPIO 19
 CLK: GPIO 18

I2C EEPROM:

Pins 27 and 28 (GPIO 0 and GPIO 1) are reserved for connecting a HAT ID EEPROM.
Do not use these pins unless you’re using an I2C ID EEPROM. Leave unconnected if you’re not
using an I2C EEPROM.

3.3. Interfacing Raspberry Pi with basic peripherals


3.4. Implementation of IoT with Raspberry Pi
Above two chapters (3.3 & 3.4) refer class notes

VMTW Page | 27

You might also like