(J2260440) FUNDAMENTALS OF INTERNET OF THINGS (OE – I)
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 popular and versatile programming languages used
worldwide today. It is classified as a high-level, interpreted, and general-purpose
programming language. This means Python is designed to be easy for humans to
read and write, it doesn’t require a compilation step before running, and it can be
used to solve a wide variety of problems across many domains.
What is Python?
Python was created to emphasize simplicity, readability, and ease of use. Unlike
many other programming languages that have complex and strict syntaxes, Python
code looks very much like plain English, making it accessible to beginners and
efficient for experts.
One of Python’s greatest strengths is its large and active community. This
community continuously contributes to a rich ecosystem of tools, tutorials, and
libraries, which extend Python’s capabilities to numerous fields such as:
Artificial Intelligence (AI) and Machine Learning
Data Science and Analytics
Web Development
Internet of Things (IoT)
Automation and Scripting
These libraries—collections of reusable code—help developers perform complex
tasks easily, saving both time and effort.
Key Features of Python
Python’s widespread adoption is due to several key features that make
programming easier and more productive:
Easy to learn syntax: The language uses simple and natural language
constructs. For example, to print something on the screen, you only need
one line of code:
print("Hello, World!")
This readability helps beginners quickly understand programming concepts
without getting bogged down by confusing syntax rules.
Interpreted language: Python runs code directly via an interpreter without a
separate compilation step. This allows for rapid testing and debugging since
programmers can write and run code immediately.
Cross-platform compatibility: Python programs can run on many operating
systems like Windows, Linux, and macOS without needing changes. This
makes Python a very flexible language for development.
Multiple programming paradigms: Python supports different programming
styles including:
o Object-Oriented Programming (OOP): Organizing code into classes
and objects to model real-world entities.
o Procedural Programming: Writing sequential instructions and
functions.
o Functional Programming: Using functions as first-class objects,
supporting higher-order functions and immutability.
This flexibility allows programmers to choose the most suitable approach for their
projects.
Basic Python Syntax and Concepts
Python’s syntax is designed for clarity and ease of use. Some basic concepts include:
Variables: Containers for storing data values. For example:
x = 10
Here, the variable x stores the integer value 10.
Data types: Python supports several built-in data types such as:
o int — integers, e.g., 5, -3
o float — decimal numbers, e.g., 3.14
o str — strings or text, e.g., "Python"
o list — ordered collections, e.g., [1, 2, 3]
o dict — key-value pairs, e.g., {"name": "Alice", "age": 25}
Control structures: These guide the program’s flow by making decisions or
repeating tasks:
o If statements for conditional execution:
if x > 5:
print("x is greater than 5")
o For loops to iterate over a sequence:
for i in range(3):
print(i)
o While loops to repeat until a condition is false:
count = 0
while count < 3:
print(count)
count += 1
Functions: Blocks of reusable code defined using the def keyword:
def greet():
print("Hi there!")
You can call this function anytime by writing greet(), which executes the print
statement inside.
Libraries: Python comes with many pre-built modules you can import to add
functionality, such as:
import math
print(math.sqrt(16)) # Outputs: 4.0
Why Python is Ideal for IoT
The Internet of Things (IoT) connects everyday objects to the internet so they can
collect, share, and act on data. Python is particularly well-suited for IoT
development because of:
Light-weight and fast execution: Python runs efficiently on small, resource-
constrained devices like the Raspberry Pi, which is a popular platform for IoT
projects.
Strong support for Raspberry Pi: The Raspberry Pi community recommends
Python as the main programming language, and many tutorials and libraries
are available specifically for it.
Hardware interfacing made easy: Libraries like RPi.GPIO and gpiozero
enable developers to interact with hardware components (sensors, LEDs,
motors) using simple Python commands. For example:
python
CopyEdit
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH) # Turn on LED connected to pin 18
This straightforward control makes Python ideal for beginners and experts
building IoT systems.
What is Raspberry Pi?
Raspberry Pi is a low-cost, credit-card-sized computer developed by the Raspberry
Pi Foundation in the UK. It plugs into a monitor or TV and uses a standard keyboard
and mouse. It can do everything a regular desktop computer can do — like browsing
the internet, playing videos, creating spreadsheets, word processing, and even
playing games!
But the most exciting part is: It is widely used for electronics projects and IoT
(Internet of Things).
Key Features of Raspberry Pi
The Raspberry Pi is a small, affordable, and powerful single-board computer
developed for learning and prototyping. Despite its small size, it comes with a range
of features that make it suitable for both educational and real-world IoT projects.
One of its main features is the ARM-based processor, which allows it to run a full
operating system like Linux and handle tasks such as programming, web browsing,
or automation. Depending on the model, it includes RAM ranging from 512MB to
8GB, suitable for light to heavy tasks.
Instead of a hard drive, Raspberry Pi uses a microSD card for storage, making it
flexible and portable. It has USB ports to connect peripherals like a keyboard,
mouse, or USB drive. An HDMI port allows connection to a monitor for graphical
interface access.
Modern models also include built-in Wi-Fi and Bluetooth, enabling wireless
communication — essential for IoT applications. Most importantly, the board
features GPIO (General Purpose Input/Output) pins, which allow users to connect
LEDs, sensors, and motors, making it ideal for electronics and automation projects.
Key Features of Raspberry Pi
Feature Description
💻 Processor ARM-based processor; efficient and low-power. Enables
running a full OS and apps.
🧠 RAM Memory ranges from 512MB to 8GB (depending on
model); supports multitasking.
📦 Storage Uses a microSD card as a hard drive to store the OS and
files.
🔌 USB Ports Connects peripherals like keyboard, mouse, USB drives,
and cameras.
🌐 HDMI Port Outputs display to a monitor or TV; supports HD and dual-
screen (in newer models).
📡 Wi-Fi & Built-in wireless connectivity for networking and device
Bluetooth pairing.
⚡ GPIO Pins Programmable pins to control hardware like LEDs, sensors,
and motors.
🔋 Power Supply Powered via micro-USB or USB-C; typically 5V 2.5A – 3A
depending on model.
💽 Operating Supports OS like Raspberry Pi OS (Linux), Ubuntu,
System Windows IoT Core.
🧠 Expandability Can be extended using HATs (Hardware Attached on Top)
for sensors, displays, etc.
✅ Comparison: Raspberry Pi vs Arduino
🔍 Feature / 🧠 Raspberry Pi ⚙️ Arduino
Aspect
Type of Device Full Linux-based single-board computer Microcontroller-based development
board
Processor ARM-based CPU (Quad-core or better) Simple microcontroller (e.g.,
ATmega328)
Operating System Runs Linux (e.g., Raspberry Pi OS) No OS; runs a single program at a
time
Programming Supports Python, C, Java, Node.js, etc. Mostly C/C++ (Arduino IDE)
Language
Multitasking ✅ Yes (can run multiple programs) ❌ No (only one sketch/program
runs at a time)
Connectivity Built-in Wi-Fi, Bluetooth, Ethernet (in Needs external modules for Wi-
most models) Fi/Bluetooth
Memory & Storage RAM (512MB–8GB), storage via Very limited RAM (2KB–8KB), no
microSD card onboard storage
USB & HDMI USB ports, HDMI output for No USB host or HDMI support
Support monitor/keyboard
Camera Interface CSI port for Pi Camera module No camera support directly
Complex Projects Suitable for web servers, databases, Best for simple control tasks (LEDs,
and IoT apps motors)
Real-Time ❌ Not real-time (due to OS latency) ✅ Real-time response (no OS delay)
Applications
Ease of Learning Ideal for beginners in Linux, Python, IoT Ideal for beginners in electronics and
C/C++
Power Higher (requires 5V/2.5A or more) Lower (can run on batteries easily)
Consumption
Cost Generally higher ($35 and up) Lower (starts around $5–$20)
GPIO PINS
GPIO stands for General Purpose Input/Output.
These are the physical pins located on the Raspberry Pi board that allow it to connect with and
control external electronic devices like LEDs, sensors, motors, and more.
🧠 Basic Idea
Think of GPIO pins as the interface between the Raspberry Pi and the real world.
You can program these pins using Python or other languages to:
Send signals (output) – e.g., turn ON an LED
Receive signals (input) – e.g., detect a button press
Raspberry Pi's GPIO (General Purpose Input/Output) pins are used for connecting
the Pi to external devices and circuits. These pins can be configured as inputs or
outputs to read data from or send data to external components, says a helpful
tutorial on Raspberry Pi. Most models have a 40-pin header, with 26 dedicated to
GPIO, and the rest for power, ground, and other functions
Most modern Raspberry Pi boards (like Pi 3, 4, and 5) have a 40-pin GPIO header.
Here’s a simplified classification:
Pin Type Description Number of Pins
Power Pins 3.3V and 5V output power 2 (5V), 2 (3.3V)
Ground GND – used to complete electrical 8
Pins circuits
GPIO Pins Programmable digital I/O 26
Special Pins I2C, SPI, UART (for sensors & modules) Several (shared with
GPIOs)
💡 GPIO Pin Types Explained
1. Input Pin
o Reads data from a device (e.g., button, sensor).
o Code example:
GPIO.setup(17, GPIO.IN)
value = GPIO.input(17)
2. Output Pin
o Sends data to a device (e.g., LED, buzzer).
o Code example:
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)
⚠️ Important Notes
GPIO pins operate at 3.3V logic. Applying more than 3.3V can damage the Pi.
Always connect GND properly in circuits.
Use resistors with LEDs and sensors to avoid short circuits or damage.
Libraries like RPi.GPIO or GPIO Zero are used in Python to program the pins.
🛠️ Common GPIO Applications
Component GPIO Usage Example
LED Output pin to turn ON/OFF
Button Input pin to detect press
Temperature Sensor Input (reads analog or digital data)
Servo Motor PWM signal from output GPIO
Buzzer Output signal to make sound
📘 Mini Example: Blink an LED
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
while True:
GPIO.output(18, GPIO.HIGH) # Turn ON LED
time.sleep(1)
GPIO.output(18, GPIO.LOW) # Turn OFF LED
time.sleep(1)
Interfacing Raspberry Pi with Basic Peripherals
Introduction
Interfacing means connecting the Raspberry Pi to external devices so it can
communicate with the outside world. Raspberry Pi’s GPIO pins, USB ports, HDMI,
audio jack, and other interfaces make it easy to connect various input and output
peripherals.
✅ What Are Peripherals?
Peripherals are external devices that connect to the Raspberry Pi to either provide input, output,
or both. These can be:
🧠 Input Devices – Send data to the Raspberry Pi (e.g., buttons, sensors)
💡 Output Devices – Receive data from the Raspberry Pi (e.g., LEDs, buzzers)
🔁 Input/Output Devices – Can both send and receive data (e.g., touchscreens)
To connect these peripherals, Raspberry Pi uses various interfaces like GPIO pins, USB ports,
HDMI, I2C, SPI, UART, and CSI.
🔌 Common Peripherals and Their Interfaces
commonly used peripherals with their interfacing method and usage:
🧠 Peripheral ⚙️ Interface Used 📌 Function / Application
LED GPIO (Digital Output) Used for visual status indicators or
blinking
Push Button GPIO (Digital Input) Used to take user input (ON/OFF)
Buzzer GPIO (Output) Generates sound alerts for
notifications
DHT11/DHT22 GPIO (Input) Measures temperature and
Sensor humidity
Ultrasonic Sensor GPIO (Trigger & Echo Pins) Measures distance using sound
waves
Motion Sensor (PIR) GPIO (Input) Detects human motion
Camera Module CSI (Camera Serial Interface) Captures images or videos
Keyboard / Mouse USB Ports Provides user input for GUI or
terminal
HDMI Display / HDMI Port Displays output from Raspberry Pi
Monitor
I2C/SPI Devices GPIO with I2C or SPI Protocol Interfaces with advanced sensors,
RTC, OLEDs
Wi-Fi / Bluetooth Built-in (on newer models) or Enables wireless communication
via USB dongle
Motor / Servo / GPIO + Driver Circuit Used for automation or robotics
Relay control
🧠 Importance of Interfaces
1. GPIO (General Purpose Input Output)
Provides pins for controlling and receiving signals from digital components.
Used for LEDs, buttons, sensors, etc.
Can be programmed using Python (RPi.GPIO or gpiozero libraries).
2. I2C and SPI
Allow Raspberry Pi to communicate with multiple sensors and modules.
Ideal for devices that send structured data (e.g., temperature sensors, RTC modules).
3. USB Ports
Used for connecting standard peripherals like keyboards, mouse, cameras, Wi-Fi dongles,
etc.
4. HDMI and Audio Out
HDMI sends video output to monitors or TVs.
Audio jack or HDMI can transmit audio signals.
5. CSI and DSI
CSI is used for the official Pi Camera module.
DSI is used for connecting touchscreen displays.
🛠 Real-World Applications
🏠 Home Automation – Controlling lights, fans, or doors using GPIO with relays.
🌦 Weather Station – Using temperature, humidity, and air quality sensors.
🧠 Smart Security – Camera module + motion sensor for surveillance.
👨🏫 Educational Kits – Buttons, LEDs, buzzers for learning electronics.
🤖 Robotics – Motor control via GPIO using motor drivers.
Implementation of IoT with Raspberry Pi
The Internet of Things (IoT) is revolutionizing how devices interact with the physical
world by enabling them to sense, process, and transmit data over the internet. One
of the most popular platforms for building IoT projects is the Raspberry Pi—a low-
cost, compact, and powerful computer that supports a wide range of applications.
The diagram titled "Implementation of IoT with Raspberry Pi" clearly illustrates the
core workflow involved in a typical IoT setup using Raspberry Pi, Python, sensors,
and cloud computing.
1. Raspberry Pi as the Central Unit
At the heart of the system is the Raspberry Pi, represented in the image as a small
green board with USB, HDMI, and GPIO ports. It serves as the IoT gateway or the
brain of the project. The Raspberry Pi is responsible for interfacing with sensors,
running the control logic, and transmitting data to the internet.
It is capable of running a full operating system (usually Raspberry Pi OS, based on
Linux) and supports programming languages like Python, making it ideal for IoT
prototyping and deployment.
2. Interfacing with Sensors
Connected to the Raspberry Pi is a sensor module, which collects real-world data
such as temperature, humidity, motion, or light. In the diagram, the sensor is shown
sending data to the Raspberry Pi through its GPIO pins. These pins allow the Pi to
interface directly with both digital and analog sensors.
This sensor data is raw and needs to be processed and interpreted before it
becomes useful. That’s where the software layer comes into play.
3. Python Script for Data Processing
A Python script, as depicted in the flowchart, runs on the Raspberry Pi. Python is
chosen because it is easy to learn, has strong library support, and integrates well
with hardware. The script performs the following tasks:
Reads data from the sensor.
Formats and processes the data.
Prepares it for uploading to the cloud.
The Python script acts as the intermediate software layer between the physical
sensors and the cloud.
4. Uploading Data to the Cloud
Once processed, the data is sent over the internet to a cloud server, which is
represented as a blue cloud and black server box in the diagram. The internet
connection can be established via Ethernet, WiFi, or even mobile networks (using
dongles or HATs).
Cloud services like ThingSpeak, Google Firebase, AWS IoT, or Microsoft Azure can
store, analyze, and visualize this data. This enables users to:
Monitor data remotely in real-time.
Trigger alerts based on conditions.
Perform long-term data analytics for insights.
5. Overall Workflow
To summarize the image's flow:
Sensor collects environmental data.
Raspberry Pi receives and processes this data.
A Python program formats and manages the data flow.
Data is sent via the internet to the cloud, enabling remote access and monitoring.
PROJECTS ON Implementation of IoT with Raspberry Pi
1.Project: Blinking of LED using Raspberry Pi (IoT Implementation)
🔍 Objective:
To blink an LED using Raspberry Pi, demonstrating a basic IoT implementation
where Raspberry Pi controls hardware through GPIO (General Purpose
Input/Output) pins.
🧠 Concept Overview:
This project shows how Raspberry Pi acts as a controller in an IoT system. By
controlling GPIO pins via Python code, you can send signals to external components
like LEDs, sensors, etc. It is the first step toward home automation, smart devices,
and sensor networks.
💡 Components Required:
Component Quantity
Raspberry Pi (any model) 1
Breadboard 1
LED 1
220-ohm Resistor 1
Jumper wires Few
⚙️ Circuit Diagram:
1. Connect the anode (long leg) of the LED to GPIO 17 (physical pin 11) of
Raspberry Pi.
2. Connect the cathode (short leg) to one end of the resistor.
3. Connect the other end of the resistor to GND (physical pin 6).
📊 GPIO Pin Reference (BCM vs BOARD):
BOARD mode uses physical pin numbering.
BCM mode uses GPIO number.
We will use BCM mode in this project.
🧠 Python Code (Using GPIO Library):
import RPi.GPIO as GPIO
import time
# Set GPIO mode to BCM
GPIO.setmode(GPIO.BCM)
# Set GPIO 17 as Output
LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)
# Blink LED 5 times
for i in range(5):
GPIO.output(LED_PIN, GPIO.HIGH) # Turn LED on
print("LED ON")
time.sleep(1) # Wait 1 second
GPIO.output(LED_PIN, GPIO.LOW) # Turn LED off
print("LED OFF")
time.sleep(1) # Wait 1 second
# Cleanup GPIO settings
GPIO.cleanup()
📝 Explanation of Code:
Line Description
import RPi.GPIO Imports the GPIO control module.
GPIO.setmode(GPIO.BCM) Uses GPIO numbering.
GPIO.setup(17, GPIO.OUT) Sets GPIO 17 as an output pin.
Line Description
GPIO.output(17, GPIO.HIGH) Turns the LED ON.
GPIO.output(17, GPIO.LOW) Turns the LED OFF.
GPIO.cleanup() Resets all GPIO pins used.
🌐 IoT Relevance:
This basic LED blinking can be extended by:
o Controlling LED from a mobile app using WiFi.
o Turning the LED ON/OFF using cloud platforms (like Blynk,
ThingSpeak).
o Setting timers or sensors to automate lighting.
Project 2: Push Button Controlled LED using Raspberry Pi (Digital Input & Output)
🎯 Objective:
To demonstrate how Raspberry Pi can read digital input from a push button and
control an LED output based on the input state — a core concept in IoT-based
automation systems.
📘 Project Description:
When you press a button, the Raspberry Pi detects it and turns ON an LED. When
the button is released, the LED turns OFF.
This introduces:
Digital input (button)
Digital output (LED)
Real-time decision-making with Raspberry Pi and Python
🧠 Components Required:
Component Quantity
Raspberry Pi 1
LED 1
Push Button 1
220-ohm Resistor 1
10k-ohm Resistor 1
Breadboard 1
Jumper wires Few
⚙️ Circuit Connections:
1. LED:
o Anode (long leg) → GPIO 17
o Cathode → Resistor → GND
2. Push Button:
o One side of the button → GPIO 18
o Other side → GND
o Connect a 10kΩ pull-up resistor between GPIO 18 and 3.3V (or use
software pull-up in code)
🧠 Python Code:
import RPi.GPIO as GPIO
import time
# Use BCM pin numbering
GPIO.setmode(GPIO.BCM)
# Set pin numbers
LED_PIN = 17
BUTTON_PIN = 18
# Set pin modes
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Enable
internal pull-up
print("Push the button to turn ON the LED...")
try:
while True:
button_state = GPIO.input(BUTTON_PIN)
if button_state == GPIO.LOW:
GPIO.output(LED_PIN, GPIO.HIGH) # LED ON
print("Button Pressed → LED ON")
else:
GPIO.output(LED_PIN, GPIO.LOW) # LED OFF
print("Button Released → LED OFF")
time.sleep(0.1)
except KeyboardInterrupt:
print("Program stopped")
finally:
GPIO.cleanup()
🔍 Code Explanation:
Code Element Explanation
GPIO.setup(..., GPIO.IN) Sets button pin as input
GPIO.PUD_UP Enables internal pull-up resistor
GPIO.input(...) Reads the button state
GPIO.output(...) Turns LED ON or OFF
time.sleep(0.1) Delay for stable reading
try...except Ensures clean shutdown
🌐 IoT Relevance & Real-Time Application:
This is a basic prototype for smart switches, security systems, or doorbell
notifications.
You can connect the button state to cloud services (like Adafruit IO or Blynk)
to notify users when a button is pressed.
With Wi-Fi, the LED could be triggered remotely or automated using IoT
logic.
🏠 Real-Life Scenario:
Imagine the button is a door sensor:
When someone opens the door, the sensor triggers the button state (LOW).
Raspberry Pi turns ON an alert LED, and can also send a message to your
phone via the cloud.