[go: up one dir, main page]

0% found this document useful (0 votes)
13 views12 pages

Fiot U 3

This document introduces Python programming and Raspberry Pi, highlighting Python's features such as being an easy-to-learn, high-level, and versatile language. It discusses the Raspberry Pi as a low-cost mini-computer capable of interfacing with various peripherals and executing Python code, along with its hardware components and GPIO pins. Additionally, it covers the implementation of IoT using Raspberry Pi, including examples like blinking an LED through Python scripts.
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)
13 views12 pages

Fiot U 3

This document introduces Python programming and Raspberry Pi, highlighting Python's features such as being an easy-to-learn, high-level, and versatile language. It discusses the Raspberry Pi as a low-cost mini-computer capable of interfacing with various peripherals and executing Python code, along with its hardware components and GPIO pins. Additionally, it covers the implementation of IoT using Raspberry Pi, including examples like blinking an LED through Python scripts.
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/ 12

UNIT-III

Introduction to Python programming: Introduction to Raspberry Pi, Interfacing


Raspberry Pi with basic peripherals, Implementation of IoT with Raspberry Pi.

Introduction to Python Programming

Python is one of the most dynamic and versatile programming languages available in the
industry today. Since its inception in the 1990s, Python has become hugely popular and even
today there are thousands who are learning this Object-Oriented Programming language. If you
are new to the world of programming, you have already heard the buzz it has created in recent
times because of the features of Python and must be wondering what makes this programming
language special.

Python is an object-oriented programming language that is designed in C. By nature, it is a high-


level programming language that allows for the creation of both simple as well as complex
operations. Along with this Python comes inbuilt with a wide array of modules as well as
libraries which allows it to support many different programming languages like Java, C, C++,
and JSON.

Python is a general-purpose high level programming language and suitable for providing a solid
foundation to the reader in the area of cloud computing. The main characteristics of Python are:

1) Multi-paradigm programming language.

2) Python supports more than one programming paradigms including object- oriented
programming and structured programming.

3) Interpreted Language.

4) Python is an interpreted language and does not require an explicit compilation step.

5) The Python interpreter executes the program source code directly, statement by statement, as a
Processor or scripting engine does.

6) Interactive Language

7) Python provides an interactive mode in which the user can submit commands at the Python
prompt and interact with the interpreter directly
Features of Python

As a programming language, the features of Python brought to the table are many. Some of the

most significant features of Python are:

Easy to Code: Python is a very developer-friendly language which means that anyone and
everyone can learn to code it in a couple of hours or days. As compared to other object-oriented
programming languages like Java, C, C++, and C#, Python is one of the easiest to learn. Open
Source and Free: Python is an open-source programming language which means that anyone can
create and contribute to its development. Python has an online forum where thousands of coders
gather daily to improve this language further. Along with this Python is free to download and use
in any operating system, be it Windows, Mac or Linux.

Support for GUI: GUI or Graphical User Interface is one of the key aspects of any programming
language because it has the ability to add flair to code and make the results more visual. Python
has support for a wide array of GUIs which can easily be imported to the interpreter, thus making
this one of the most favorite languages for developers.

Object-Oriented Approach: One of the key aspects of Python is its object-oriented approach.
This basically means that Python recognizes the concept of class and object encapsulation thus
allowing programs to be efficient in the long run.

High-Level Language: Python has been designed to be a high-level programming language,


which means that when you code in Python you don’t need to be aware of the coding structure,
architecture as well as memory management.

Integrated by Nature: Python is an integrated language by nature. This means that the python
interpreter executes codes one line at a time. Unlike other object-oriented programming
languages, we don’t need to compile Python code thus making the debugging process much
easier and efficient. Another advantage of this is, that upon execution the Python code is
immediately converted into an intermediate form also known as byte-code which makes it easier
to execute and also saves runtime in the long run.

Highly Portable: Suppose you are running Python on Windows and you need to shift the same to
either a Mac or a Linux system, then you can easily achieve the same in Python without having
to worry about changing the code. This is not possible in other programming languages, thus
making Python one of the most portable languages available in the industry.

Highly Dynamic: As mentioned in an earlier paragraph, Python is one of the most dynamic
languages available in the industry today. What this basically means is that the type of a variable
is decided at the run time and not in advance. Due to the presence of this feature, we do not need
to specify the type of the variable during coding, thus saving time and increasing efficiency.
Extensive Array of Library: Out of the box, Python comes inbuilt with a large number of
libraries that can be imported at any instance and be used in a specific program. The presence of
libraries also makes sure that you don’t need to write all the code yourself and can import the
same from those that already exist in the libraries.

Support for Other Languages: Being coded in C, Python by default supports the execution of
code written in other programming languages such as Java, C, and C#, thus making it one of the
versatile in the industry.

Python Data Types:

Data types are the classification or categorization of data items. Data types represent a kind of
value which determines what operations can be performed on that data. Numeric, non-numeric
and Boolean (true/false) data are the most used data types. However, each programming
language has its own classification largely reflecting its programming philosophy.

Python has the following standard or built-in data types:

Built-in Data Types

In programming, data type is an important concept. Variables can store data of different types,
and different types can do different things. Python has the following data types built-in by
default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: Dict

Set Types: set, frozenset

Boolean Type: Bool

Binary Types: bytes, bytearray, memoryview

Numeric

A numeric value is any representation of data which has a numeric value. Python identifies three
types of numbers:

Integer: Positive or negative whole numbers (without a fractional part)

Float: Any real number with a floating point representation in which a fractional

component is denoted by a decimal symbol or scientific notation


Complex number: A number with a real and imaginary component represented as x+yj.

x and y are floats and j is -1(square root of -1 called an imaginary number)

Boolean

Data with one of two built-in values True or False. Notice that 'T' and 'F' are capital. True and
false are not valid booleans and Python will throw an error for them.

Sequence Type

A sequence is an ordered collection of similar or different data types. Python has the following
built-in sequence data types:

String: A string value is a collection of one or more characters put in single, double or

triple quotes.

List : A list object is an ordered collection of one or more data items, not necessarily of

the same type, put in square brackets.

Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily

of the same type, put in parentheses.

Dictionary

A dictionary object is an unordered collection of data in a key:value pair form. A collection of

such pairs is enclosed in curly brackets. For example: {1:"Steve", 2:"Bill",

3:"Ram", 4: "Farha"}

type() function

Python has an in-built function type() to ascertain the data type of a certain value. For example,

enter type(1234) in Python shell and it will return <class 'int'>, which means 1234 is an integer
value. Try and verify the data type of different values in Python shell, as shown below.

Mutable and Immutable Objects

Data objects of the above types are stored in a computer's memory for processing. Some of these

values can be modified during processing, but contents of others can't be altered once they are
created in the memory. Number values, strings, and tuple are immutable, which means their
contents can't be altered after creation.
On the other hand, collection of items in a List or Dictionary object can be modified. It is
possible to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable
objects.

types of Data Structures in Python

Python allows its users to create their own Data Structures enabling them to have full control
over their functionality. The most prominent Data Structures are Stack, Queue, Tree, Linked List
and so on which are also available to you in other programming languages. So now that you
know what are the types available to you, why don’t we move ahead to the Data Structures and
implement them using Python.

Built-in Data Structures

As the name suggests, these Data Structures are built-in with Python which makes programming
easier and helps programmers use them to obtain solutions faster. Let’s discuss each of them in
detail.

Lists

Lists are used to store data of different data types in a sequential manner. There are addresses
assigned to every element of the list, which is called as Index. The index value starts from 0 and
goes on until the last element called the positive index. There is also negative indexing which
starts from -1 enabling you to access elements from the last to first. Let us now understand lists
better with the help of an example program.

Creating a list

To create a list, you use the square brackets and add elements into it accordingly. If you do not
pass any elements inside the square brackets, you get an empty list as the output.

1
2
3
4
my_list = [] #create empty list
print(my_list)
my_list = [1, 2, 3, 'example', 3.132] #creating list with data
print(my_list)
Output:
[]
[1, 2, 3, ‘example’, 3.132]
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 purpose I/O pins. Since Raspberry Pi runs Linux operating system, it
supports Python "out of the box".
 The Raspberry Pi was developed by the Raspberry Pi Foundation, a UK charity, with the
goal of encouraging the teaching of basic computer science, and Eben Upton is the
founder and inventor of the Raspberry Pi.
 The Raspberry Pi 5, announced in September 2023, is a significantly more powerful
version of its predecessor, the Pi 4, featuring a 2.4 GHz quad-core 64-bit ARM Cortex
A76 CPU and a VideoCore VII GPU, with a new in-house designed I/O controller.

Raspberry Pi mainly consists of the following blocks:

Processor: Raspberry Pi uses Broadcom BCM2835 system on chip which is an ARM


processor and Video core Graphics Processing Unit (GPU). It is the heart of the
Raspberry Pi which controls the operations of all the connected devices and handles all
the required computations.
HDMI: High Definition Multimedia Interface is used for transmitting video or digital
audio data to a computer monitor or to digital TV. This HDMI port helps Raspberry Pi to
connect its signals to any digital device such as a monitor digital TV or display through
an HDMI cable.
GPIO ports: General Purpose Input Output ports are available on Raspberry Pi which
allows the user to interface various I/P devices.
4 types of GPIO Pins
1) Digital I/O Pins: These pins can be used to send or receive digital signals (high or
low, 1 or 0).
2) PWM (Pulse Width Modulation) Pins: These pins can output a signal with varying
duty cycles, allowing for precise control of devices like LEDs and motors.
3) I2C (Inter-Integrated Circuit) Pins: These pins facilitate communication with other
devices using the I2C protocol.
4) SPI (Serial Peripheral Interface) Pins: These pins enable communication with other
devices using the SPI protocol.
Audio output: An audio connector is available for connecting audio output devices such
as headphones and speakers.
USB ports: This is a common port available for various peripherals such as a mouse,
keyboard, or any other I/P device. With the help of a USB port, the system can be
expanded by connecting more peripherals.
SD card: The SD card slot is available on Raspberry Pi. An SD card with an operating
system installed is required for booting the device.
Ethernet: The ethernet connector allows access to the wired network, it is available only
on the model B of Raspberry Pi.
Power supply: A micro USB power connector is available onto which a 5V power
supply can be connected.
Camera module: Camera Serial Interface (CSI) connects the Broadcom processor to the
Pi camera.
Display: Display Serial Interface (DSI) is used for connecting LCD to Raspberry Pi
using 15 15-pin ribbon cables. DSI provides a high-resolution display interface that is
specifically used for sending video data.
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
Interfacing Raspberry Pi with basic peripherals

Interfacing with basic peripherals on a Raspberry Pi involves connecting external devices


like LEDs, sensors, or buttons to the Raspberry Pi's General Purpose Input/Output
(GPIO) pins. This allows the Pi to interact with the physical world by receiving input
from sensors and controlling output devices.
Process:
1. Understanding GPIO Pins:
 The Raspberry Pi has a row of pins, called GPIO pins, that act as interfaces
between the Pi and external components.
 These pins can be configured as either inputs (to receive signals) or outputs (to
send signals). .
2. Connecting Peripherals:
 Identify the correct pins: Consult a pinout diagram to determine which GPIO pins
to use for your specific devices.
 Use appropriate cables: Connect peripherals using jumper wires or other suitable
cables.
 Consider power requirements: Ensure the peripheral's voltage and current needs
are compatible with the Raspberry Pi's GPIO pins or external power supply.
3. Software Setup:
 Install necessary libraries: Libraries like RPi.GPIO or pigpio provide functions for
controlling the GPIO pins in Python.
 Write code to interact with peripherals:
 Use the library functions to set pin modes (input or output), read values from
input pins, and control the state of output pins.
 Example: Interfacing with an LED:
 Connect the positive (long) leg of the LED to a GPIO pin through a resistor (to
limit current).
 Connect the negative (short) leg to a ground pin.
 In your code, set the GPIO pin as an output and turn it on or off.
4. Common Peripherals:
 LEDs: Simple output devices that can be used to indicate status or provide visual
feedback.
 Sensors: Devices that detect physical properties like temperature, light, or motion.
 Buttons: Input devices that trigger actions when pressed.
 LCD screens: Display information from the Raspberry Pi.
 Motors: Allow the Raspberry Pi to control movement.
5. Communication Protocols:
 SPI, I2C, UART: These are communication protocols that enable the Raspberry
Pi to communicate with more complex peripherals.
 SPI:
A synchronous serial communication protocol often used for connecting displays,
sensors, and flash storage.
 I2C:
An inter-integrated circuit protocol used for communication between multiple devices.
 UART:
A universal asynchronous receiver/transmitter protocol used for serial communication.
Implementation of IoT with Raspberry Pi.

An IoT implementation with a Raspberry Pi involves connecting sensors to the Pi,


reading data from them, and then processing and sending that data, often to a remote
server or cloud platform, for further analysis or control. The Raspberry Pi acts as a
gateway, connecting physical sensors to the digital world.
1) Blinking an LED
To blink an LED connected to a Raspberry Pi, you can use a Python script that toggles
the LED's state (on and off) at regular intervals.
CODE
import RPi.GPIO as GPIO
import time
# Set the GPIO mode to BOARD (physical pin numbering)
GPIO.setmode(GPIO.BOARD)
# Set the GPIO pin number for the LED (e.g., pin 18)
led_pin = 18
# Set the LED pin as an output
GPIO.setup(led_pin, GPIO.OUT)
try:
while True:
# Turn the LED on
GPIO.output(led_pin, GPIO.HIGH)
time.sleep(1) # Wait for 1 second

# Turn the LED off


GPIO.output(led_pin, GPIO.LOW)
time.sleep(1) # Wait for 1 second
except KeyboardInterrupt:
# Clean up GPIO on script exit (e.g., Ctrl+C)
GPIO.cleanup()
Explanation:
 Import necessary libraries: RPi.GPIO for controlling the GPIO pins and time for
pausing execution.
 Set GPIO mode: GPIO.setmode(GPIO.BOARD) sets the numbering scheme for
the GPIO pins. In this case, it uses the physical pin numbering on the header.
 Set up the LED pin: GPIO.setup(led_pin, GPIO.OUT) configures the specified
pin (e.g., 18) as an output pin.while True: loop: This creates an infinite loop that
continuously executes the code inside.
 Turn the LED on: GPIO.output(led_pin, GPIO.HIGH) sets the specified pin to a
high voltage (typically 3.3V), turning the LED on.
time.sleep(1): Pauses the script for 1 second.
 Turn the LED off: GPIO.output(led_pin, GPIO.LOW) sets the specified pin to a
low voltage (typically 0V), turning the LED off.
time.sleep(1): Pauses the script for another second.
try...except KeyboardInterrupt: This block handles the case where you stop the script
using Ctrl+C.
 GPIO.cleanup(): This line resets the GPIO pins to their default state, releasing any
resources used by the script. This is important to prevent issues when running
other programs or when the script is stopped unexpectedly.
To run this code:
 Connect an LED and a resistor (e.g., 220-ohm or 330-ohm) to the Raspberry Pi's
GPIO pins. Make sure the longer leg of the LED (the anode) is connected to a
resistor, and the other end of the resistor is connected to a GPIO pin (like pin 18).
The shorter leg of the LED (the cathode) should be connected to a ground pin
(e.g., pin 6 or 9).
 Save the code as a Python file (e.g., led_blink.py).
 Open a terminal and navigate to the directory where you saved the file.
 Run the script using sudo python3 led_blink.py.
 This will make the LED blink on and off repeatedly. To stop the program, press
Ctrl+C in the terminal.

2) Temperature Sensing

A Python program for a Raspberry Pi to read temperature from a DS18B20 sensor


involves using the w1thermsensor library and interacting with the device file. First,
ensure the one-wire interface is enabled in the Raspberry Pi's configuration. Then, the
Python script reads the temperature from the sensor, handling potential errors and
displaying the result.

CODE

import time

from w1thermsensor import W1ThermSensor

sensor = W1ThermSensor()

while True:

temperature = sensor.get_temperature()

print(f"The temperature is {temperature:.2f} degrees Celsius")

time.sleep(1)

Run the Code:

Save the Python code (e.g., as temp_sensor.py).

Run it using python3 temp_sensor.py.


Explanation:

 The code imports the w1thermsensor library, which simplifies interaction with
the DS18B20 sensor.
 It initializes the sensor object.
 The while True loop continuously reads the temperature using
sensor.get_temperature().
 The temperature is printed to the console with two decimal places.
time.sleep(1) pauses the execution for 1 second before the next reading.

You might also like