0% found this document useful (0 votes)
10 views13 pages

FIoT - Unit-3

The document provides an introduction to Python programming and Raspberry Pi, highlighting Python's features, applications, and basic syntax, as well as the Raspberry Pi's capabilities, history, and uses in IoT. It outlines the steps to get started with both Python and Raspberry Pi, including installation, programming, and interfacing with peripherals. Additionally, it covers the implementation of IoT projects using Raspberry Pi, detailing hardware and software requirements, programming logic, and security considerations.
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)
10 views13 pages

FIoT - Unit-3

The document provides an introduction to Python programming and Raspberry Pi, highlighting Python's features, applications, and basic syntax, as well as the Raspberry Pi's capabilities, history, and uses in IoT. It outlines the steps to get started with both Python and Raspberry Pi, including installation, programming, and interfacing with peripherals. Additionally, it covers the implementation of IoT projects using Raspberry Pi, detailing hardware and software requirements, programming logic, and security considerations.
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/ 13

Introduction to Python Programming

What is Python?
Python is a high-level, interpreted, general-purpose programming language created by
Guido van Rossum and released in 1991. It is known for its readable syntax, simplicity, and
versatility, making it a popular choice for beginners and professionals alike. Python
supports multiple programming paradigms, including procedural, object-oriented, and
functional programming.

Python is widely used in:


- Web development
- Data science
- Artificial intelligence and machine learning
- Automation
- Game development
- Networking and cybersecurity

Key Features of Python


- Easy to Learn: Clean and human-readable syntax.
- Interpreted: Executes code line-by-line, useful for debugging.
- Dynamically Typed: No need to declare variable types explicitly.
- Extensive Libraries: Rich ecosystem of built-in and third-party libraries.
- Cross-platform: Works on Windows, Linux, and macOS.
- Open Source: Free to use and distribute.

Basic Syntax and Examples


Printing a Message:

print("Hello, World!")

Variables and Data Types:

x = 10 # Integer
name = "Alice" # String
pi = 3.14 # Float
is_valid = True # Boolean

Conditional Statement:
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
Loops:

For Loop:

for i in range(5):
print(i)

While Loop:
count = 0
while count < 5:
print(count)
count += 1

Function:

def greet(name):
return f"Hello, {name}!"

print(greet("Alice"))

Popular Python Libraries and Their Uses


| Library | Usage |
|-------------- |----------------------------------|
| math | Mathematical operations |
| random | Random number generation |
| datetime | Working with date and time |
| os | File and system operations |
| numpy | Numerical computing and arrays |
| pandas | Data manipulation and analysis |
| matplotlib | Data visualization |
| tkinter | GUI development |
| sklearn | Machine learning |

Applications of Python
- Web Development – using Django, Flask
- Data Science & Analytics – using Pandas, NumPy, Matplotlib
- Machine Learning & AI – using TensorFlow, scikit-learn, PyTorch
- Scripting & Automation – automating repetitive tasks
- Game Development – with Pygame
- Internet of Things (IoT) – Python on Raspberry Pi
- Cybersecurity – penetration testing and scripting
Why Learn Python?
- Easy for beginners with clean syntax
- Massive online support and community
- High demand in the job market
- Used in both industry and academia
- Flexible and powerful for a wide range of applications

Getting Started with Python


1. Install Python:
Download the latest version from https://www.python.org.

2. Choose an IDE:
Options include:
- IDLE (comes with Python)
- VS Code
- PyCharm
- Jupyter Notebook

3. Start Practicing:
Use online platforms like:
- HackerRank
- LeetCode
- Codecademy
- Replit

Introduction to Raspberry Pi
What is Raspberry Pi?
The Raspberry Pi is a small, affordable, single-board computer developed by the Raspberry
Pi Foundation in the UK. Originally designed to promote computer science education in
schools and developing countries, the Raspberry Pi has evolved into a powerful platform
used in a wide variety of applications including IoT, robotics, home automation, and
embedded systems.

It is about the size of a credit card, yet powerful enough to perform tasks such as word
processing, programming, and even multimedia playback.

History and Evolution


The first Raspberry Pi model (Model B) was released in 2012. Since then, several models
have been introduced including Raspberry Pi 2, 3, 4, and the latest Raspberry Pi 5. Each
generation brought improvements in CPU speed, memory, USB ports, GPIO pins, and
wireless connectivity.
Variants like Raspberry Pi Zero offer minimalistic, cost-effective options for embedded
projects.

Key Features of Raspberry Pi


- ARM-based processor

- GPIO (General Purpose Input Output) pins for hardware interfacing

- HDMI output for display

- USB ports for keyboard, mouse, and other peripherals

- MicroSD card slot for storage and OS

- Ethernet and Wi-Fi (on newer models)

- Camera and display interface ports

Operating System and Software


Raspberry Pi typically runs a Linux-based OS called Raspberry Pi OS (formerly Raspbian).
Other compatible OSes include Ubuntu, Windows IoT Core, and even Android.

Popular programming languages on Raspberry Pi:

- Python

- C/C++

- Java

- Scratch (for educational use)

Tools such as Thonny IDE and VS Code are commonly used for software development.

Applications of Raspberry Pi
1. **Education** – Teaching programming, electronics, and robotics.

2. **IoT Projects** – Smart home automation, sensor data collection.

3. **Media Center** – Kodi and Plex for media playback.

4. **Web Server Hosting** – Lightweight web applications using Flask or Django.

5. **Game Emulation** – RetroPie for emulating classic game consoles.

6. **AI & Machine Learning** – TensorFlow Lite for edge AI applications.

7. **Networking** – VPN servers, network monitoring tools.


Getting Started with Raspberry Pi
1. **Purchase a Raspberry Pi Kit** – Includes board, power supply, microSD card, HDMI
cable, and case.

2. **Install the OS** – Use Raspberry Pi Imager to write Raspberry Pi OS onto the microSD
card.

3. **Boot and Configure** – Connect peripherals (monitor, keyboard, mouse) and power it
on.

4. **Begin Development** – Start programming with Python or any preferred language


using pre-installed tools.

5. **Explore Projects** – Try tutorials on automation, sensors, and Python-based systems.

Why Use Raspberry Pi?


- Low cost and energy efficient

- Versatile and extensible

- Strong educational and maker community

- Excellent documentation and tutorials

- Perfect for prototyping and learning about hardware-software integration


Interfacing Raspberry pi with basic peripherals
To interface a Raspberry Pi with basic peripherals, you'll need a monitor, keyboard,
mouse, and SD card with a Raspberry Pi OS image, and then connect them via USB and
HDMI ports, respectively.

1. Essential Hardware
 Raspberry Pi: The core computer.
 Micro SD Card: Stores the operating system (Raspberry Pi OS).
 Monitor: For displaying output (use HDMI).
 Keyboard and Mouse: For input and control (use USB).
 Power Supply: To power the Raspberry Pi.
 Optional: Ethernet cable for internet access, headphones or speakers.
2. Connecting the Peripherals
 Monitor: Connect the monitor to the Raspberry Pi's HDMI port.
 Keyboard and Mouse: Connect the keyboard and mouse to the Raspberry Pi's USB
ports.
 Power Supply: Connect the power supply to the Raspberry Pi.
 SD Card: Insert the micro SD card into the Raspberry Pi.
 Optional: Connect ethernet cable to the ethernet port.
3. Getting Started
 Power On: Plug in the power supply and the Raspberry Pi will boot up from the SD card.
 Operating System: The Raspberry Pi will boot into the Raspberry Pi OS.
 Basic Functionality: You can now use the keyboard and mouse to interact with the
Raspberry Pi OS.
4. Additional Peripherals
 Cameras:
The Raspberry Pi can interface with cameras, including the Pi Camera module.
 Sensors:
You can connect various sensors (temperature, light, etc.) to the Raspberry Pi's GPIO
pins.
 Other Devices:
You can connect other devices like RFID readers, LCD displays, and more.
 SPI:
Serial Peripheral Interface (SPI) can be used to communicate with high-speed
peripherals.
Implementation of IoT with Raspberry Pi
Introduction
The Internet of Things (IoT) connects physical devices to the internet, enabling data
exchange and remote control. Raspberry Pi—a low-cost, credit card-sized computer—is a
widely used platform for IoT due to its affordability, versatility, and GPIO (General
Purpose Input Output) capabilities.

Hardware Requirements
- Raspberry Pi (3/4 or newer)
- MicroSD Card with Raspberry Pi OS
- Power supply
- Sensors (e.g., DHT11 for temperature/humidity, PIR for motion)
- Actuators (LEDs, Relays)
- Wi-Fi or Ethernet
- Jumper wires and breadboard

Software Requirements
- Operating System: Raspberry Pi OS
- Programming Language: Python
- Libraries:
- RPi.GPIO: Control GPIO pins
- Adafruit_DHT: Read from DHT sensors
- requests, paho-mqtt: For network communication
- Cloud Platforms: Thingspeak, Blynk, AWS IoT, Azure IoT Hub

Steps to Implement IoT with Raspberry Pi

1. Setting Up Raspberry Pi
Install Raspberry Pi OS using Raspberry Pi Imager. Enable SSH and connect to Wi-Fi.
Update packages using `sudo apt update && sudo apt upgrade`.
2. Connecting Sensors and Actuators
Connect sensors (e.g., DHT11) to GPIO pins. Write Python code to read sensor values.
Test output via terminal or LED indication.

3. Programming the IoT Logic


Example: Reading temperature from DHT11 and sending it to a cloud platform like
ThingSpeak:

import Adafruit_DHT
import requests

sensor = Adafruit_DHT.DHT11
pin = 4

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)


if humidity and temperature:
print(f"Temp={temperature}C Humidity={humidity}%")
# Send to cloud

requests.get(f"https://api.thingspeak.com/update?api_key=YOUR_K
EY&field1={temperature}")

4. Cloud Integration
Create a channel on a cloud platform like ThingSpeak or Blynk. Use HTTP or MQTT
protocols for communication. Visualize real-time data using dashboards.

5. Automation and Alerts


Set rules (e.g., trigger buzzer if temperature exceeds a threshold). Integrate with services
like IFTTT for notifications via email or SMS.

Applications
- Smart Home Automation (lights, security, climate control)
- Health Monitoring Systems (temperature, heartbeat sensors)
- Agriculture (soil moisture, irrigation control)
- Industrial IoT (predictive maintenance, monitoring)

Security Considerations
- Use secure APIs (HTTPS)
- Change default Raspberry Pi credentials
- Enable firewalls and disable unused ports
Examples
1. Blinking 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) # LED on

time.sleep(1)

GPIO.output(18, GPIO.LOW) # LED off

time.sleep(1)

2. Read Temperature & Humidity from DHT11


import Adafruit_DHT

sensor = Adafruit_DHT.DHT11

pin = 4 # GPIO pin where DHT11 is connected

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

if humidity is not None and temperature is not None:

print(f"Temp={temperature}°C, Humidity={humidity}%")

else:

print("Failed to retrieve data")

3. Motion Detection with PIR Sensor


import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

PIR_PIN = 17

GPIO.setup(PIR_PIN, GPIO.IN)
print("Waiting for motion...")

while True:

if GPIO.input(PIR_PIN):

print("Motion detected!")

time.sleep(2)

4. Send Sensor Data to ThingSpeak


import Adafruit_DHT
import requests
sensor = Adafruit_DHT.DHT11
pin = 4
api_key = 'YOUR_THINGSPEAK_API_KEY'
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity and temperature:
print("Uploading to ThingSpeak...")
url =
f"https://api.thingspeak.com/update?api_key={api_key}&field1={temperature}&field2={hu
midity}"
requests.get(url)

5. Control LED with Button

import RPi.GPIO as GPIO


GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.OUT)

while True:
button_state = GPIO.input(23)
GPIO.output(24, not button_state)

You might also like