0% found this document useful (0 votes)
28 views

Iot 3

Uploaded by

ayushisingh2186
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Iot 3

Uploaded by

ayushisingh2186
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Module 3: IoT Physical Devices and Endpoints 6 hours

What is an IoT device, Basic building block of an IoT device, Introduction to Raspberry Pi, about the
board, Linux on Raspberry pi, - Raspberry pi Interfaces (Serial, SPI, I2C), Programming Raspberry pi with
python- with focus on controlling output-LED, reading input from pins-Switch and LDR.
An IoT (Internet of Things) device is a physical object that is embedded with
sensors, software, and other technologies, enabling it to connect and exchange
data with other devices or systems over the internet or a local network. These
devices can be anything from everyday household items to industrial machines
and are typically designed to gather data, automate processes, or provide
remote control functionality.

Examples of IoT devices include:

• Smart home devices: Thermostats, security cameras, smart light bulbs, and
smart appliances (like refrigerators or washing machines) that can be
controlled via a smartphone or voice assistants.
• Wearable technology: Smartwatches and fitness trackers that monitor
health metrics like heart rate, sleep patterns, and physical activity.
• Industrial IoT devices: Sensors on manufacturing equipment that track
performance, detect anomalies, and predict maintenance needs.
• Healthcare IoT devices: Medical equipment like insulin pumps, remote
patient monitoring systems, and connected medical devices that track
health data in real-time.
Basic building block of an IoT device
The basic building blocks of an IoT device are the essential components that allow it to
sense, process, and communicate data. These blocks work together to enable the dev
1. Sensors/Actuators
• Sensors: These are used to collect data from the environment, such as
temperature, humidity, motion, light, pressure, or other physical parameters. They
convert physical signals into electrical ones.
• Actuators: These components perform actions based on the processed data, like
turning on a light, adjusting the temperature, or controlling a motor.
ice to perform its IoT functions. Here are the main building blocks:
2. Microcontroller/Microprocessor
• The microcontroller (MCU) or microprocessor (MPU) acts as the
brain of the IoT device. It processes the data gathered by sensors and
can execute commands to control actuators. The microcontroller is
responsible for running embedded software, controlling peripherals,
and managing communication protocols.
• Popular examples include Arduino, ESP8266, ESP32, Raspberry Pi, or
specific MCUs like the ARM Cortex series.
3. Connectivity Module
• This allows the IoT device to connect and communicate with the
internet or other devices. Connectivity can be wireless or wired,
depending on the application.
• Common communication protocols include:
– Wi-Fi: For home IoT devices like smart thermostats.
– Bluetooth: For short-range communication, like wearables.
– Zigbee/Z-Wave: For low-power, short-range communication in
smart home systems.
– Cellular (4G/5G): For IoT devices requiring long-range
communication.
– LoRa, NB-IoT: For low-power, wide-area networks (LPWAN) for
remote sensing applications.
4. Power Source
• The IoT device needs a reliable power source to function. Depending
on the application, this can be a battery, mains power, or even solar
power for remote, energy-efficient devices.

5. Memory/Storage
• Memory is used to store the device's firmware, collected data, and
configurations. This includes:
– RAM: Temporary memory for processing data.
– Flash/EEPROM: Permanent storage for firmware and data that
needs to be retained when the device is powered off.

6. Embedded Software/Firmware
• The software or firmware controls how the IoT device operates. It
manages the sensors, processes data, and handles communication
with other devices or cloud platforms. This software is usually
programmed in languages like C, C++, or Python, depending on the
platform.
7. Cloud/Edge Services (Optional but Critical for IoT)
• Cloud: Many IoT devices are designed to send data to a cloud service for analysis,
storage, or remote control. The cloud also allows for scalability, as well as
additional processing and data analytics.
• Edge Computing: Some IoT devices can process data locally (at the edge) to reduce
latency or the need for constant internet connectivity, making the system more
efficient.
Module-3

Introduction to Raspberry Pi

The Raspberry Pi is a small, affordable single-board computer developed by the Raspberry Pi


Foundation in the UK. It was originally designed to promote teaching basic computer science in
schools but has since become popular for a wide variety of applications, from hobby projects to
professional embedded systems.

Key Features

 Small Size: The Raspberry Pi is about the size of a credit card, making it highly portable and easy
to integrate into various projects.
 Low Cost: It is very affordable, with models starting at around $5 (Raspberry Pi Zero) and going
up to about $35 for the more powerful models.
 Open-source: Both the hardware and software are based on open-source principles,
encouraging community involvement and customization.

Main Components

1. CPU (Processor): The Raspberry Pi features an ARM-based CPU. Recent models, such
as the Raspberry Pi 4, use a quad-core Cortex-A72 processor, which is quite powerful for
its size and price.
2. RAM (Memory): Depending on the model, the Raspberry Pi comes with varying
amounts of RAM, from 512 MB to 8 GB, making it suitable for different levels of
computational tasks.
3. Storage: The Raspberry Pi does not have onboard storage like a traditional computer.
Instead, it uses a microSD card for the operating system and file storage. This makes it
highly flexible since the OS can easily be swapped by changing the SD card.
4. Connectivity: The Raspberry Pi includes multiple connectivity options:
o USB Ports: For connecting peripherals such as keyboards, mice, and external storage
devices.
o HDMI Output: To connect a monitor or TV.
o Ethernet and Wi-Fi: For networking and internet connectivity (depending on the
model).
o GPIO (General Purpose Input/Output) Pins: These allow for connection to external
sensors, motors, and other electronic components, making the Raspberry Pi ideal for IoT
and robotics projects.

Operating System

 The Raspberry Pi typically runs Raspberry Pi OS (formerly Raspbian), which is a Linux-based


operating system optimized for the Pi's hardware.
 However, it can also run other OSs such as Ubuntu, Windows 10 IoT Core, or specialized OSs
depending on the project needs.
Popular Models

1. Raspberry Pi 4: The latest and most powerful model, with up to 8 GB of RAM, dual HDMI
output, and USB 3.0 support.
2. Raspberry Pi Zero: A smaller and cheaper version, ideal for lightweight projects and IoT
applications.
3. Raspberry Pi 3B+: Still widely used for projects, with built-in Wi-Fi and Bluetooth.

Applications of Raspberry Pi

1. Learning and Education: A great tool for teaching programming, electronics, and computer
science.
2. IoT (Internet of Things): Due to its GPIO pins and networking capabilities, the Pi is frequently
used in IoT projects to control sensors and devices remotely.
3. Home Automation: It can be used to automate lighting, security cameras, or appliances.
4. Media Center: With software like Kodi, the Pi can serve as a home media center to stream
videos, music, or play games.
5. Robotics: The Pi can be used to control robots and drones by interfacing with motors and
sensors.
6. Network Servers: It can host lightweight web servers, file servers, or VPNs.

Why Use Raspberry Pi?

 Affordable: It's an inexpensive way to explore computing and electronics.


 Versatile: Supports a wide range of projects, from basic programming to complex IoT and
robotics.
 Large Community: There’s a massive global community offering tutorials, support, and open-
source projects.
 Low Power Consumption: Its power efficiency makes it suitable for 24/7 operations, such as in
smart home projects or web servers.
The Raspberry Pi board is a compact and versatile single-board computer that provides all the
essential components of a fully functional computer in a small package. Let’s dive into the
layout, components, and functionality of the Raspberry Pi board:

Key Components of the Raspberry Pi Board

1. Processor (CPU)

 The heart of the Raspberry Pi is its ARM-based processor. In the Raspberry Pi 4, it is a quad-core
Cortex-A72 64-bit processor that runs at 1.5 GHz, making it powerful enough for multitasking,
media playback, programming, and running light servers.

2. Graphics Processing Unit (GPU)

 The GPU on Raspberry Pi boards is typically a VideoCore IV for older models or VideoCore VI for
Raspberry Pi 4, capable of handling multimedia tasks, including video playback at 4K and
hardware-accelerated OpenGL.

3. Memory (RAM)

 Raspberry Pi boards come with different amounts of RAM, depending on the model:
o Raspberry Pi 4: Available in 2 GB, 4 GB, and 8 GB variants.
o Older models, like the Raspberry Pi 3, come with 1 GB of RAM.
 The RAM is used for running applications and the operating system.

4. Storage (MicroSD Card Slot)

 Instead of a traditional hard drive or SSD, the Raspberry Pi uses a microSD card to store the
operating system, files, and data. The microSD card slot is located on the underside of the
board. This allows for flexible and easy storage upgrades.

5. GPIO (General Purpose Input/Output) Pins

 One of the most significant features of the Raspberry Pi board is the 40 GPIO pins, which allow
users to connect external hardware like sensors, LEDs, motors, and other electronic
components.
 These pins can be programmed to interact with external devices, making the Pi ideal for
robotics, home automation, and IoT applications.

6. Power Input

 The Raspberry Pi is powered via a USB-C port (for Raspberry Pi 4) or a micro-USB port (for
earlier models). It typically requires a 5V, 3A power supply to run efficiently, especially for
newer models.
7. USB Ports

 Raspberry Pi boards come with multiple USB ports for connecting peripherals like keyboards,
mice, USB drives, and other accessories:
o Raspberry Pi 4 features 2 USB 3.0 ports (for high-speed data transfer) and 2 USB 2.0
ports.
o Earlier models only have USB 2.0 ports.

8. HDMI Port(s)

 Raspberry Pi boards include HDMI output for connecting to a monitor or TV. The Raspberry Pi 4
has 2 micro-HDMI ports, allowing dual-monitor setups with 4K output. Older models typically
have a single full-size HDMI port.

9. Ethernet and Wi-Fi

 Ethernet Port: For wired internet connectivity, the Raspberry Pi has a built-in Gigabit Ethernet
port on the Raspberry Pi 4 and 3B+.
 Wi-Fi: Built-in Wi-Fi (802.11ac) is included in the Raspberry Pi 4 and 3 models for wireless
networking.
 Bluetooth: The Raspberry Pi 4 and 3 models also feature Bluetooth 5.0 for wireless peripherals.

10. Audio Output

 The Raspberry Pi has an integrated 3.5mm audio jack that provides analog stereo sound. You
can also transmit audio via the HDMI port for digital sound output.

11. Camera and Display Interfaces

 Camera Interface (CSI): The Raspberry Pi has a dedicated Camera Serial Interface (CSI)
connector for attaching the official Raspberry Pi Camera Module.
 Display Interface (DSI): There’s also a Display Serial Interface (DSI) for connecting the
Raspberry Pi touchscreen display.

12. Power Over Ethernet (PoE)

 The Raspberry Pi 3B+ and 4 support Power over Ethernet (PoE) via an optional PoE HAT
(Hardware Attached on Top), allowing the board to be powered through the Ethernet cable.

13. LED Indicators

 Raspberry Pi boards feature a few small LEDs that indicate the status of power and activity:
o PWR (Power): Shows that the board is powered on.
o ACT (Activity): Flashes when the SD card is being read or written.
Physical Layout

The layout of the Raspberry Pi board is well-organized, with components neatly placed for
accessibility:

 GPIO pins are located along one edge of the board.


 USB and Ethernet ports are on one side, making it easy to connect peripherals.
 HDMI and audio ports are on another side for connecting display and sound output.
Linux on Raspberry pi

Running Linux on a Raspberry Pi is a great way to explore embedded systems, programming, and various
development tasks. Raspberry Pi primarily uses Raspberry Pi OS (previously known as Raspbian), which
is a Debian-based Linux distribution optimized for the Pi. However, other distributions like Ubuntu, Arch
Linux, and even Kali Linux can also be installed.

Here’s how to get started with Linux on a Raspberry Pi:

1. Choose a Linux Distribution

 Raspberry Pi OS: This is the recommended OS and comes in both Desktop and Lite (minimal
command-line interface) versions.
 Ubuntu: A full-fledged Linux distribution, suitable if you need more power and broader Linux
support.

2. Download the OS Image

 Visit the Raspberry Pi website to download Raspberry Pi OS or other distributions.


 If using Ubuntu, download from the official Ubuntu Pi page: Ubuntu for Raspberry Pi.

3. Write the Image to an SD Card

 Use a tool like Raspberry Pi Imager, Balena Etcher, or Win32DiskImager to flash the OS
onto an SD card.
 Minimum SD card size should be 8GB, but 16GB or 32GB is recommended for more space.

4. Booting the Raspberry Pi

 Insert the SD card into the Raspberry Pi, connect your monitor, keyboard, and mouse, then power
it on.
 The Pi will boot from the SD card and load the OS.

5. Initial Setup

 On the first boot, you’ll be prompted to set up system preferences like the country, time zone, Wi-
Fi, and passwords.
 For Raspberry Pi OS, you’ll also get access to useful programming tools like Thonny IDE,
Python, and Scratch.

6. Explore and Develop

 You can install software through the apt package manager (sudo apt update && sudo
apt upgrade), develop in Python, C/C++, or any language supported by Linux.
 Raspberry Pi OS also supports GPIO pins programming, making it ideal for embedded projects
and interfacing with hardware like sensors or actuators.
Running Linux on a Raspberry Pi has numerous advantages when it comes to IoT (Internet of
Things) and embedded systems development. The combination of Raspberry Pi’s hardware
capabilities and the versatility of Linux makes it an ideal platform for prototyping and deploying
real-world IoT and embedded solutions. Here's why:

1. Cost-Effective IoT Prototyping and Development

 Affordable Hardware: Raspberry Pi provides a low-cost entry point for IoT


development. Whether you are building a smart home system, remote monitoring, or an
industrial automation project, Raspberry Pi delivers enough computational power at a
fraction of the cost compared to other hardware.
 Prototyping: For embedded system developers, Raspberry Pi allows rapid prototyping of
ideas. With Linux as the OS, it is easier to scale from a simple proof-of-concept to more
complex, production-level IoT devices.

2. Versatile Connectivity Options

 Built-in Networking: Most Raspberry Pi models come with Ethernet and Wi-Fi out of
the box, essential for IoT devices that need network access for cloud communication,
device-to-device interaction, or remote monitoring.
 Bluetooth: IoT devices often require local communication (e.g., with sensors or mobile
devices), and Bluetooth is natively supported in most Raspberry Pi models running
Linux, enabling easy integration of wireless peripherals.

3. Linux Support for IoT Protocols and Software

 Protocol Support: With Linux running on Raspberry Pi, developers can easily
implement and experiment with various IoT protocols such as MQTT, CoAP,
HTTP/HTTPS, LoRa, and others.
 Edge Computing: Linux provides support for tools like Docker, Kubernetes, and Node-
RED. This makes it possible to run IoT workloads and manage services on the edge,
reducing the need for constant cloud communication.
 Cloud Integration: Linux distributions like Raspberry Pi OS can easily integrate with
major cloud services (AWS IoT, Google Cloud IoT, Azure IoT Hub), allowing IoT
devices to send telemetry data or receive commands from cloud-based applications.

4. GPIO Access and Hardware Control

 GPIO Pins: One of the most important features of Raspberry Pi for embedded systems is
the GPIO (General Purpose Input/Output) pins, which allow direct connection to
hardware components such as sensors, actuators, motors, and other peripherals.
 Peripheral Communication: Linux allows you to interface with a wide range of
communication protocols (e.g., SPI, I2C, UART), enabling the Pi to interact with
microcontrollers (such as the 8051 you work with), sensors, and embedded devices. This
is essential for developing custom hardware solutions and real-time embedded
applications.
 Real-Time Applications: By leveraging Linux tools, it is possible to develop real-time
IoT applications, such as environmental monitoring or home automation, where fast and
reliable data from sensors are critical.

5. Cross-Platform Development and Flexibility

 Multi-Language Support: Linux supports a variety of programming languages


commonly used in IoT and embedded systems development, such as Python, C/C++,
Java, and Node.js. This gives flexibility in choosing the right language for your IoT or
embedded application.
 Cross-Development: You can develop code on your desktop Linux machine and easily
transfer it to the Raspberry Pi, thanks to the similar Linux environment. This flexibility
speeds up the development and testing process.

6. Remote Management and Monitoring

 SSH Access: Linux allows you to enable SSH on the Raspberry Pi, which makes it easy
to remotely manage and monitor the device from anywhere. This is particularly valuable
in IoT deployments where devices might be in remote locations, such as environmental
sensors or remote surveillance systems.
 Automation and Scheduling: With Cron jobs and systemd, Linux offers tools for
scheduling tasks, automating system updates, and controlling the execution of IoT
services in a headless manner, essential for maintaining IoT devices in the field.

7. Security Features

 Firewall and VPN: Linux has built-in firewall capabilities, and you can easily set up
VPN or SSH tunneling for secure communication between IoT devices and remote
servers, ensuring data privacy and security.
 Secure Boot: Linux on Raspberry Pi can be configured with secure boot mechanisms and
encryption tools, making it suitable for secure IoT deployments where data protection
and device integrity are crucial.

8. Scalability for Large IoT Networks

 Distributed Systems: Linux enables the development of distributed IoT systems where
multiple Raspberry Pi devices communicate with each other over a network. This is
useful in smart cities, industrial monitoring, and other scenarios where data from multiple
devices needs to be aggregated and processed.
 Docker and Containerization: With support for Docker, you can run containerized
applications on Raspberry Pi, making it easy to deploy scalable microservices in IoT
environments. This also allows easy updating and deployment of services across a fleet of
IoT devices.

9. Community Support and Documentation


 Open-Source Community: Both the Linux and Raspberry Pi communities are vast and
active, providing extensive support for IoT and embedded development. From tutorials to
sample projects, the wealth of available knowledge helps accelerate the development
process.
 Third-Party Libraries: There are many open-source libraries and frameworks available
for working with specific sensors, devices, and IoT protocols, such as Paho MQTT for
MQTT communication, or Adafruit and SparkFun libraries for interfacing with sensors
and hardware modules.

10. Power Efficiency

 For IoT applications where power consumption is critical, Raspberry Pi, especially the Pi
Zero models, can be optimized for low power usage. While Linux is running, you can
configure the system to enter low-power states when idle or schedule periodic wake-ups
to perform tasks, making it suitable for battery-operated IoT devices.

Real-World Applications of Raspberry Pi in IoT and Embedded Systems

 Smart Home Automation: Control lighting, security systems, and appliances remotely
via Linux-powered Raspberry Pi systems integrated with cloud services or local control
via MQTT.
 Environmental Monitoring: Use sensors connected to the Raspberry Pi to measure
temperature, humidity, air quality, and other environmental factors, transmitting data to
cloud services for analysis.
 Industrial IoT (IIoT): Monitor and control industrial machinery, collect sensor data, and
integrate with enterprise systems using Raspberry Pi and Linux as a cost-effective
embedded controller.
 Wearable Devices: Develop wearables or other health-monitoring devices by integrating
sensors with Raspberry Pi and collecting data via Linux-based applications.
Raspberry pi Interfaces (Serial, SPI, I2C)

The Raspberry Pi provides several communication interfaces for interacting with other devices,
sensors, and microcontrollers. These interfaces include Serial (UART), SPI, and I2C. Each has
its own use cases and advantages, making Raspberry Pi a versatile platform for embedded
systems and IoT applications.

1. Serial (UART - Universal Asynchronous Receiver-Transmitter)

Overview

The UART interface on the Raspberry Pi allows asynchronous serial communication with
external devices like microcontrollers (e.g., 8051), GPS modules, Bluetooth modules, or other
serial devices. It uses TX (Transmit) and RX (Receive) pins to send and receive data.

Key Features

 Point-to-point communication: UART is used for one-to-one communication between two


devices.
 No clock signal: Communication is asynchronous, meaning it does not require a shared clock
signal.
 Configurable baud rates: The speed of communication (baud rate) is configurable, making it
flexible for various devices.

Raspberry Pi Pins

 TXD (Pin 8): Transmit data.


 RXD (Pin 10): Receive data.

Applications

 Interfacing with serial devices like GPS receivers, GSM modules, or microcontrollers.
 Debugging and communication through serial consoles.
 Connecting to Bluetooth modules like HC-05 via UART.

How to Use

 Enable the serial interface by running sudo raspi-config, selecting Interfacing Options, and
enabling the serial port.
 Use libraries like pySerial in Python or minicom to send/receive data via the serial port.
2. SPI (Serial Peripheral Interface)

Overview

SPI is a synchronous, full-duplex protocol primarily used for high-speed communication


between the Raspberry Pi and peripheral devices such as sensors, displays, and memory cards. It
uses a master-slave architecture, with the Pi acting as the master.

Key Features

 Full-duplex communication: Data can be sent and received simultaneously.


 Synchronous communication: A shared clock signal (SCLK) keeps the data in sync.
 Multiple slaves: SPI can communicate with multiple devices using Chip Select (CS) lines.

Raspberry Pi Pins

 MOSI (Pin 19): Master Out Slave In (data from Pi to peripheral).


 MISO (Pin 21): Master In Slave Out (data from peripheral to Pi).
 SCLK (Pin 23): Clock line.
 CE0 (Pin 24): Chip Select 0 (used to select the slave device).
 CE1 (Pin 26): Chip Select 1 (used to select another slave).

Applications

 Interfacing with high-speed sensors (e.g., temperature sensors like MAX6675, accelerometers
like ADXL345).
 Driving displays, such as OLED or TFT screens.
 Flash memory chips or SD cards for data storage.
 Communicating with shift registers and analog-to-digital converters (ADCs).

How to Use

 Enable the SPI interface by running sudo raspi-config and enabling SPI in the Interfacing
Options.
 Use the spidev library in Python or C for controlling the SPI interface.

3. I2C (Inter-Integrated Circuit)

Overview

I2C is a multi-device, half-duplex, synchronous communication protocol. Unlike SPI, I2C only
requires two wires for communication, making it suitable for situations where multiple devices
need to share the same bus with minimal wiring.
Key Features

 Synchronous communication: Like SPI, I2C uses a clock signal to synchronize data transfer.
 Half-duplex communication: Data transmission happens in one direction at a time.
 Multi-master and multi-slave: Multiple devices (masters and slaves) can share the same
communication lines.
 Addressing: Each slave device on the I2C bus has a unique 7-bit or 10-bit address, allowing for
communication with multiple devices using the same two wires.

Raspberry Pi Pins

 SDA (Pin 3): Serial Data Line (transmits data).


 SCL (Pin 5): Serial Clock Line (synchronizes data transmission).

Applications

 Interfacing with low-speed peripherals like EEPROMs, temperature sensors (e.g., DS1307), light
sensors (e.g., BH1750), or other microcontrollers.
 Communication with LCD displays that support I2C.
 Reading sensor data from multiple I2C devices on the same bus (e.g., IMU sensors).

How to Use

 Enable the I2C interface by running sudo raspi-config, selecting Interfacing Options, and
enabling I2C.
 Install the I2C tools by running sudo apt-get install i2c-tools.
 Use the SMBus library in Python for easy I2C communication.
Controlling an LED using Python on a Raspberry Pi is one of the most common beginner
projects. It helps introduce how to control the GPIO (General Purpose Input/Output) pins to
interact with hardware. Here’s a step-by-step guide to get started with Python for controlling an
LED:

Hardware Setup

You’ll need:

1. Raspberry Pi (any model with GPIO pins).


2. LED (any basic LED will work).
3. Resistor (330Ω or 220Ω to limit current and prevent the LED from burning out).
4. Breadboard and jumper wires.

Connecting the LED to Raspberry Pi

 Step 1: Identify the GPIO pins on your Raspberry Pi. GPIO pin 17 (Pin 11 on the GPIO header) will
be used as an example to control the LED.
 Step 2: Connect the positive leg (longer leg, anode) of the LED to GPIO pin 17.
 Step 3: Connect the negative leg (shorter leg, cathode) of the LED to one end of the resistor.
 Step 4: Connect the other end of the resistor to a ground (GND) pin on the Raspberry Pi (e.g.,
Pin 6 or Pin 9).

The circuit should look like this:

 GPIO 17 (Pin 11) ➔ Anode (Long leg of LED).


 Cathode (Short leg of LED) ➔ Resistor (220Ω/330Ω) ➔ Ground (Pin 6 or 9).

Python Programming for LED Control

Step 1: Install GPIO Library

The RPi.GPIO library is used to interact with the GPIO pins in Python.

1. Open a terminal on your Raspberry Pi.


2. Install the library if it's not already installed:

sudo apt-get update


sudo apt-get install python3-rpi.gpio

Step 2: Write the Python Code

Now, let's write a basic Python program to control the LED.

1. Open the terminal or use a text editor (like Thonny) and create a new Python file, say
led_control.py:
nano led_control.py

2. Write the following code to control the LED:

import RPi.GPIO as GPIO


import time

# Set the GPIO mode


GPIO.setmode(GPIO.BCM) # Use the Broadcom pin numbering
GPIO.setwarnings(False)

# Set up GPIO pin 17 as an output pin


LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)

# Turn the LED on


print("Turning LED on")
GPIO.output(LED_PIN, GPIO.HIGH)
time.sleep(2) # Keep the LED on for 2 seconds

# Turn the LED off


print("Turning LED off")
GPIO.output(LED_PIN, GPIO.LOW)

# Clean up GPIO settings


GPIO.cleanup()

Code Explanation

 GPIO.setmode(GPIO.BCM): Configures the GPIO pin numbering system to use the Broadcom
(BCM) numbering.
 GPIO.setup(LED_PIN, GPIO.OUT): Sets up GPIO pin 17 as an output pin to control the LED.
 GPIO.output(LED_PIN, GPIO.HIGH): Turns the LED on by sending a high voltage signal to GPIO
17.
 GPIO.output(LED_PIN, GPIO.LOW): Turns the LED off by sending a low voltage signal to GPIO
17.
 time.sleep(2): Keeps the LED on for 2 seconds before turning it off.
 GPIO.cleanup(): Resets the GPIO pin state to avoid warnings or issues when running the script
again.

Step 3: Run the Code

Save the Python file (Ctrl+X, then Y to save in nano) and run it using the terminal:

python3 led_control.py

You should see the LED turn on for 2 seconds and then turn off.
Blinking LED Example

To make the LED blink continuously, you can modify the code as follows:

To make the LED blink continuously, you can modify the code as follows:

import RPi.GPIO as GPIO


import time

# Set the GPIO mode


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# Set up GPIO pin 17 as an output pin


LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)

try:
while True:
# Turn the LED on
GPIO.output(LED_PIN, GPIO.HIGH)
print("LED ON")
time.sleep(1) # LED stays on for 1 second

# Turn the LED off


GPIO.output(LED_PIN, GPIO.LOW)
print("LED OFF")
time.sleep(1) # LED stays off for 1 second

except KeyboardInterrupt:
# If Ctrl+C is pressed, exit the loop and clean up
GPIO.cleanup()
print("Exiting and cleaning up GPIO")
Controlling an LED with a button using a Raspberry Pi is a great way to introduce input and
output control with the GPIO pins. In this project, the LED will turn on when the button is
pressed, and turn off when it is released. Here's how to set up and program it.

Hardware Required:

1. Raspberry Pi (any model with GPIO pins).


2. LED.
3. Resistor (330Ω or 220Ω for the LED).
4. Push button.
5. Resistor (10kΩ for the button as a pull-down resistor).
6. Breadboard and jumper wires.

Circuit Setup:

1. LED Circuit Setup

 Connect the positive leg (anode) of the LED to GPIO pin 17.
 Connect the negative leg (cathode) of the LED to one end of the 330Ω resistor.
 Connect the other end of the resistor to the ground (GND) pin on the Raspberry Pi.

2. Button Circuit Setup

 One terminal of the button is connected to GPIO pin 18 (Pin 12).


 The other terminal is connected to the ground (GND).
 Use a 10kΩ resistor as a pull-down resistor, connecting the GPIO pin 18 to ground. This ensures
that the GPIO pin reads a LOW state (0) when the button is not pressed.

Circuit Diagram:

1. GPIO 17 (Pin 11) ➔ Anode of LED.


2. Cathode of LED ➔ Resistor (330Ω) ➔ GND (Pin 6).
3. GPIO 18 (Pin 12) ➔ Button ➔ GND (Pin 14).
4. GPIO 18 ➔ 10kΩ resistor ➔ GND (acting as pull-down resistor).

Python Code to Control LED with a Button

1. Open a terminal and create a Python script, e.g., led_button.py:

nano led_button.py

2. Write the following code:


import RPi.GPIO as GPIO
import time

# Set the GPIO mode


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# Define pin numbers


LED_PIN = 17 # Pin to control the LED
BUTTON_PIN = 18 # Pin to read the button state

# Set up the LED pin as an output


GPIO.setup(LED_PIN, GPIO.OUT)

# Set up the button pin as an input with a pull-down resistor


GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

try:
while True:
# Read the button state
if GPIO.input(BUTTON_PIN) == GPIO.HIGH:
# If the button is pressed, turn the LED on
GPIO.output(LED_PIN, GPIO.HIGH)
print("Button pressed - LED ON")
else:
# If the button is not pressed, turn the LED off
GPIO.output(LED_PIN, GPIO.LOW)
print("Button released - LED OFF")

# Small delay to avoid bouncing issues


time.sleep(0.1)

except KeyboardInterrupt:
# Cleanup GPIO settings when the program is terminated
GPIO.cleanup()
print("Program terminated and GPIO cleaned up")

Code Explanation

 GPIO.setmode(GPIO.BCM): Configures the GPIO pin numbering to use the BCM (Broadcom)
numbering system.
 GPIO.setup(LED_PIN, GPIO.OUT): Sets GPIO pin 17 as an output to control the LED.
 GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN): Sets GPIO pin 18 as an
input with a pull-down resistor. This ensures the GPIO pin reads LOW (0) when the button is not
pressed and HIGH (1) when the button is pressed.
 GPIO.input(BUTTON_PIN): Reads the state of the button (HIGH or LOW).
 GPIO.output(LED_PIN, GPIO.HIGH/LOW): Turns the LED on or off based on the button state.
 time.sleep(0.1): Introduces a small delay to avoid bouncing issues when pressing the button.
 GPIO.cleanup(): Resets the GPIO pin states when the program ends, preventing warnings the
next time the script is run.

Pull-down Resistor:

The 10kΩ pull-down resistor connected to GPIO pin 18 ensures that the button reads as LOW
(0) when it’s not pressed. Without this, the GPIO pin might float and give unreliable readings.
Interfacing an LDR (Light Dependent Resistor) with a Raspberry Pi involves setting up a
circuit to measure the changes in light intensity using the LDR. Since the Raspberry Pi lacks
analog input pins, you'll need to use an Analog-to-Digital Converter (ADC) like the MCP3008
to read the analog voltage signal produced by the LDR.

Here’s a step-by-step guide to interfacing an LDR with a Raspberry Pi.

Hardware Required

1. Raspberry Pi (any model).


2. LDR (Light Dependent Resistor).
3. MCP3008 ADC chip.
4. 10kΩ resistor (for the voltage divider circuit).
5. Breadboard and jumper wires.

Circuit Setup

The MCP3008 is an external ADC that communicates with the Raspberry Pi over the SPI
protocol. It converts the analog voltage from the LDR into a digital value that the Raspberry Pi
can read.

1. Voltage Divider with LDR

The LDR and a 10kΩ resistor will form a voltage divider circuit. This circuit divides the 3.3V
supply voltage based on the changing resistance of the LDR when exposed to different light
levels. The voltage across the 10kΩ resistor will vary depending on the light intensity, which can
then be measured.

2. MCP3008 Pin Connections

Here’s how to connect the MCP3008 to the Raspberry Pi:

 VDD ➔ 3.3V (Pin 1 on Raspberry Pi).


 VREF ➔ 3.3V (Pin 1).
 AGND and DGND ➔ Ground (Pin 6).
 CLK (Clock) ➔ GPIO 11 (Pin 23).
 DOUT (MISO) ➔ GPIO 9 (Pin 21).
 DIN (MOSI) ➔ GPIO 10 (Pin 19).
 CS/SHDN (Chip Select) ➔ GPIO 8 (Pin 24).

3. LDR Circuit

 One leg of the LDR goes to 3.3V.


 The other leg of the LDR connects to Channel 0 of the MCP3008 and one leg of the 10kΩ
resistor.
 The other leg of the 10kΩ resistor connects to Ground.
This forms a voltage divider, where the output is the voltage across the 10kΩ resistor, which
varies with light intensity.

Circuit Diagram

1. LDR connected to 3.3V and the junction of a 10kΩ resistor.


2. 10kΩ resistor connected to ground (GND).
3. The voltage at the junction between the LDR and the resistor is fed into Channel 0
(CH0) of the MCP3008.

Python Code to Interface LDR with MCP3008

You can use the spidev library to read data from the MCP3008 and interpret the light intensity
from the LDR.

1. First, install the necessary Python libraries:

sudo apt-get update


sudo apt-get install python3-spidev

2. Write the following Python script to read the LDR values:

import spidev
import time

# Initialize SPI
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1350000

# Function to read MCP3008 channel


def read_channel(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data

# Function to convert ADC data to voltage


def convert_to_voltage(data, places):
volts = (data * 3.3) / float(1023)
volts = round(volts, places)
return volts

try:
while True:
# Read the LDR value from channel 0
ldr_value = read_channel(0)
ldr_volts = convert_to_voltage(ldr_value, 2)

# Print out the value and voltage


print(f"LDR Value: {ldr_value}, LDR Voltage: {ldr_volts}V")

# Add a small delay to avoid flooding the console with data


time.sleep(0.5)

except KeyboardInterrupt:
spi.close()
print("Program terminated")

Code Explanation:

 SPI Initialization: The spidev library initializes the SPI bus to communicate with the
MCP3008.
 read_channel(): Reads the analog value from one of the MCP3008 channels (in this
case, Channel 0 for the LDR).
 convert_to_voltage(): Converts the raw ADC reading (0 to 1023) to a voltage (0 to
3.3V), which corresponds to the light level detected by the LDR.
 Loop: Continuously reads the LDR value and prints it to the terminal.
1. What is an IoT device? Explain its key components and give an example of its application. 5M
2. What are the basic building blocks of an IoT device? Explain each component in detail with an
example. 10M
3. Explain the different connectivity modules available for designing an IoT model, and describe
their uses. 5M
4. Explain briefly how microcontrollers and microprocessors are important for designing IoT
systems. 5M
5. Provide a comprehensive introduction to the Raspberry Pi, including its key features, main
components, and operating system. 10M
6. Discuss the popular models of the Raspberry Pi, their applications, and the reasons why the
Raspberry Pi is widely used in various projects. 5/10M
7. Describe the key components of the Raspberry Pi board, including their functions. Include a
labeled diagram to illustrate these components. 10M
8. Outline the steps to get started with Linux on a Raspberry Pi. Include details on preparation,
installation, and initial setup. 5/10M
9. Discuss the advantages of running Linux on a Raspberry Pi for IoT (Internet of Things) and
embedded systems development. 10M
10. What is the UART (Universal Asynchronous Receiver-Transmitter) interface on the Raspberry Pi,
and how is it used for communication? 5M
11. What is the I2C (Inter-Integrated Circuit) interface on the Raspberry Pi, and how is it used for
communication? 5M
12. Compare the Serial (UART), I2C, and SPI communication protocols in terms of their features,
advantages, and typical use cases. 5/10M
13. Describe the process of controlling an LED using Python on a Raspberry Pi. Include details on the
required hardware, Python code, and the steps to implement the project. 10M
14. Explain how to control an LED with a button using a Raspberry Pi. Describe the hardware setup,
the Python code needed, and how it demonstrates input and output control with GPIO pins.10M
15. How do you interface an LDR (Light Dependent Resistor) with a Raspberry Pi to measure
changes in light intensity? 5M

You might also like