Unit 1: Setting Up and GPIO Handling
1. Introduction to the Raspberry Pi Platform
The Raspberry Pi is a credit-card-sized Single Board Computer (SBC) developed by the Raspberry Pi Foundation. Unlike microcontrollers (such as Arduino or ESP32) that execute bare-metal firmware or light Real-Time Operating Systems (RTOS), the Raspberry Pi incorporates a full-featured System-on-Chip (SoC) based on the ARM architecture, running a full multitasking Linux operating system.
CODE+-----------------------------------------------------------------------------+ | SINGLE BOARD COMPUTER vs. MICROCONTROLLER | +-----------------------------------------------------------------------------+ | Characteristic | Single Board Computer (Raspberry Pi)| Microcontroller (e.g., ESP32/Arduino)| +----------------------+------------------------------------+---------------------------------------+ | Core Processing Unit | Broadcom Application Processor | Microcontroller Unit (MCU) | | Operating System | Multitasking Linux (Raspberry Pi OS)| Bare-metal firmware or FreeRTOS | | Clock Frequency | 1.5 GHz – 2.4 GHz (Multi-core) | 16 MHz – 240 MHz | | Memory (RAM) | 1 GB – 8 GB LPDDR4 | Kilobytes to a few Megabytes (SRAM) | | Primary Storage | MicroSD Card, eMMC, or NVMe SSD | Internal On-Chip Flash (4–16 MB) | | I/O Capabilities | 40-pin GPIO, DSI Display, CSI Cam, | Analog ADC, PWM, Timers, GPIO, SPI, | | | Gigabit Ethernet, USB 3.0, PCIe | I2C, UART (Low power) | | Real-Time Determinism| Non-deterministic (Linux kernel OS)| Hard real-time deterministic execution| | Power Consumption | 3.0W – 15.0W (Requires 5V/3A–5A) | Milliwatts (Ideal for battery sleep) | +-----------------------------------------------------------------------------+
2. Hardware Architecture and Board Anatomy
The modern Raspberry Pi (Raspberry Pi 4 Model B and Raspberry Pi 5) incorporates high-performance mobile computing hardware:
CODE+-----------------------------------------------------------------------------+ | RASPBERRY PI 4 HARDWARE BLOCK DIAGRAM | +-----------------------------------------------------------------------------+ | | | +---------------------------------------------------------------+ | | | 40-Pin GPIO Expansion Header | | | +---------------------------------------------------------------+ | | | | | | +--------------+ +---------------------------+ +------------+ | | | 3.3V / 5V / | | Broadcom BCM2711 SoC | | Gigabit | | | | GND Rails | <--> | Quad-core Cortex-A72 | <--> | Ethernet | | | +--------------+ | @ 1.5 GHz (ARM v8 64-bit) | | PHY (RJ45) | | | +---------------------------+ +------------+ | | | | | | +--------------------+ +-------------------+ | | v v | | +--------------+ +------------+ | | | LPDDR4 RAM | | VL805 USB3 | | | | (1/2/4/8 GB) | | Controller | | | +--------------+ +------------+ | | | | | | +--------------+ +---------------------------+ +------------+ | | | MicroSD Slot | | Dual Micro-HDMI (4Kp60) | | 2x USB 3.0 | | | | (UHS-I SDR50)| | CSI Camera / DSI Display | | 2x USB 2.0 | | | +--------------+ +---------------------------+ +------------+ | | | | | | +---------------------------------------------------------------------+ | | | USB Type-C Power Input (5V DC, minimum 3.0A recommended) | | | +---------------------------------------------------------------------+ | +-----------------------------------------------------------------------------+
2.1 The System-on-Chip (SoC)
- Raspberry Pi 4 Model B: Powered by the Broadcom BCM2711 SoC, featuring a quad-core ARM Cortex-A72 64-bit processor running at 1.5 GHz (or 1.8 GHz in newer revisions) and a VideoCore VI 3D GPU.
- Raspberry Pi 5: Powered by the Broadcom BCM2712 quad-core Cortex-A76 @ 2.4 GHz paired with the custom RP1 I/O Controller managing GPIO and peripheral buses.
3. Operating System Installation and Headless Setup
The official operating system is Raspberry Pi OS (formerly Raspbian), an optimized 32-bit or 64-bit distribution derived from Debian GNU/Linux.
3.1 Flashing with Raspberry Pi Imager
The standard deployment utility is Raspberry Pi Imager. It allows pre-configuring OS parameters directly before burning the image to a MicroSD card:
- Setting the default hostname (e.g.,
raspberrypi.local). - Creating the primary administrative user account and password (disabling the legacy insecure default
pi/raspberry). - Pre-configuring Wi-Fi network credentials (SSID and WPA2/WPA3 passphrase) and country regulatory domain.
- Enabling the SSH server for remote shell access.
3.2 Headless Configuration Mechanics
A headless setup operates the Raspberry Pi without connecting a physical monitor, keyboard, or mouse:
- Enabling SSH via the Boot Partition:
- When Raspberry Pi OS boots, the bootloader mounts the FAT32
bootpartition (labeled/bootor/boot/firmware). - If an empty file named
ssh(without any file extension) is detected in the root of the boot partition, the system automatically enables the OpenSSH server (sshd) and immediately deletes thesshfile.
- When Raspberry Pi OS boots, the bootloader mounts the FAT32
- User Credential Provisioning (
userconf.txt):- In modern Debian Bookworm/Bullseye releases, headless user creation requires a
userconf.txtfile in the boot partition containing:
username:encrypted_password_hash
- In modern Debian Bookworm/Bullseye releases, headless user creation requires a
- Connecting via Secure Shell (SSH):
bash
# Connect using mDNS hostname resolution ssh username@raspberrypi.local # Or connect via dynamic or static LAN IP address ssh username@192.168.1.105 - Remote Graphical Desktop via VNC:
- Enabled via the system configuration menu:
sudo raspi-config-> Interface Options -> VNC -> Enable. - Accessible from laptops or workstations using RealVNC Viewer on port
5900.
- Enabled via the system configuration menu:
4. Raspberry Pi 40-Pin GPIO Architecture
The Raspberry Pi exposes a standard dual-row 40-pin header providing direct access to general-purpose digital input/output lines and serial communication buses.
CODE+-----------------------------------------------------------------------------+ | 40-PIN EXPANSION HEADER PINOUT & SCHEMATIC | +-----------------------------------------------------------------------------+ | Pin # | Function / BCM Channel | Pin # | Function / BCM Channel | +-------+-------------------------+-------+-----------------------------------+ | 1 | 3.3V DC Power | 2 | 5V DC Power | | 3 | GPIO 2 (I2C1 SDA) | 4 | 5V DC Power | | 5 | GPIO 3 (I2C1 SCL) | 6 | Ground (GND) | | 7 | GPIO 4 (GPCLK0) | 8 | GPIO 14 (UART0 TXD) | | 9 | Ground (GND) | 10 | GPIO 15 (UART0 RXD) | | 11 | GPIO 17 (Digital I/O) | 12 | GPIO 18 (PCM CLK / PWM0) | | 13 | GPIO 27 (Digital I/O) | 14 | Ground (GND) | | 15 | GPIO 22 (Digital I/O) | 16 | GPIO 23 (Digital I/O) | | 17 | 3.3V DC Power | 18 | GPIO 24 (Digital I/O) | | 19 | GPIO 10 (SPI0 MOSI) | 20 | Ground (GND) | | 21 | GPIO 9 (SPI0 MISO) | 22 | GPIO 25 (Digital I/O) | | 23 | GPIO 11 (SPI0 SCLK) | 24 | GPIO 8 (SPI0 CE0) | | 25 | Ground (GND) | 26 | GPIO 7 (SPI0 CE1) | | 27 | ID_SD (I2C ID EEPROM) | 28 | ID_SC (I2C ID EEPROM) | | 29 | GPIO 5 (Digital I/O) | 30 | Ground (GND) | | 31 | GPIO 6 (Digital I/O) | 32 | GPIO 12 (PWM0) | | 33 | GPIO 13 (PWM1) | 34 | Ground (GND) | | 35 | GPIO 19 (PCM FS / PWM1) | 36 | GPIO 16 (Digital I/O) | | 37 | GPIO 26 (Digital I/O) | 38 | GPIO 20 (PCM DIN) | | 39 | Ground (GND) | 40 | GPIO 21 (PCM DOUT) | +-------+-------------------------+-------+-----------------------------------+
4.1 Electrical Specifications and 3.3V Logic Hazard
[!CAUTION]
Overvoltage Warning: All Raspberry Pi GPIO pins operate strictly at 3.3V CMOS logic levels.
- Input High Voltage (): Minimum 2.0V, Maximum 3.3V.
- Input Low Voltage (): Maximum 0.8V.
- The GPIO pins are NOT 5V tolerant. Connecting a 5V sensor output directly to a Raspberry Pi GPIO pin will permanently destroy the Broadcom SoC's internal electrostatic discharge (ESD) protection diodes and burn out the I/O bank.
- Maximum recommended drive current per individual GPIO pin is 16 mA, with the total aggregate current across all GPIO pins not exceeding 50 mA.
4.2 Pin Numbering Schemes: BCM vs. BOARD (Physical)
When addressing GPIO pins in code, developers must choose between two distinct conventions:
- Physical Pin Numbering (
GPIO.BOARD):- Refers to the physical sequential pin numbers on the 40-pin header (Pins 1 through 40).
- Advantage: Hardware-invariant across different board hardware revisions.
- Broadcom Channel Numbering (
GPIO.BCM):- Refers to the internal GPIO signal channel numbers on the Broadcom SoC (e.g., GPIO 17, GPIO 27).
- Advantage: Standard convention used in modern software libraries and hardware extension HAT specifications.
5. Digital Output Interfacing: LED Circuit Design
When driving an external load such as a Light Emitting Diode (LED), a current-limiting resistor is strictly required to prevent the LED from drawing excessive current and destroying the GPIO pin.
CODEGPIO Pin (3.3V) o | [R] Current-Limiting Resistor (e.g., 220 Ohm) | --- \ / LED (Forward Voltage Drop: Vf) --- | v --- GND (0V, Pin 6)
5.1 Current-Limiting Resistor Calculation (Ohm's Law)
According to Ohm's Law and Kirchhoff's Voltage Law:
Where:
- (Raspberry Pi digital output voltage)
- (Typical forward voltage drop of a standard red LED)
- (Safe operating forward current)
Calculation:
Standard Selection: A standard or resistor is typically selected to limit current to approximately , providing adequate brightness while staying well within the pin's 16 mA ceiling.
6. Digital Input Interfacing and Switch Debouncing
When interfacing input devices such as pushbuttons or tactile switches, the input pin must never be left electrically unconnected (floating). A floating pin acts as an antenna, picking up electromagnetic interference (EMI) and oscillating unpredictably between digital HIGH and LOW.
CODE+-----------------------------------------------------------------------------+ | PULL-UP vs. PULL-DOWN RESISTOR CIRCUITS | +-----------------------------------------------------------------------------+ | | | [INTERNAL PULL-UP (Active-LOW)] [INTERNAL PULL-DOWN (Active-HIGH)]| | | | 3.3V Rail 3.3V Rail | | | | | | [R] Pull-Up Resistor (50k) --- Pushbutton | | | o o (Normally Open) | | GPIO o---+ | | | | GPIO o---+ | | --- Pushbutton | | | o o (Normally Open) [R] Pull-Down (50k) | | | | | | GND GND | | | | * Unpressed: Pin reads HIGH (1) * Unpressed: Pin reads LOW (0) | | * Pressed: Pin reads LOW (0) * Pressed: Pin reads HIGH (1) | +-----------------------------------------------------------------------------+
6.1 Mechanical Switch Bouncing and Debouncing
Mechanical switches consist of spring-loaded metallic contacts. When pressed or released, the physical contacts do not settle instantaneously; they mechanically bounce against each other for 5 to 20 milliseconds, generating dozens of spurious high-speed digital transitions before reaching a steady state.
CODEIdeal Transition: LOW ________________________/~~~~~~~~~~~~~~~~~~ HIGH Real Bouncing Signal: LOW ________/\_/\_/\_/\_____/~~~~~~~~~~~~~~~~~~ HIGH |<-- 10ms Bouncing Window -->|
- Hardware Debouncing: Placing an RC low-pass filter (, ) and a Schmitt-trigger inverter across the switch contacts to smooth the voltage curve.
- Software Debouncing: Instructing the GPIO driver to ignore subsequent edge transitions for a refractory duration (e.g.,
bouncetime=200ms).
7. Python Programming with RPi.GPIO and gpiozero
7.1 The RPi.GPIO Library
RPi.GPIO is the classic low-level Python library for controlling Broadcom I/O pins.
pythonimport RPi.GPIO as GPIO
import time
# Pin Definitions (BCM channel mapping)
LED_PIN = 17
BUTTON_PIN = 27
# 1. Initialize Mode
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# 2. Configure Pins
GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Internal Pull-Up
# 3. Callback Function for Interrupt-Driven Event Detection
def button_callback(channel):
print("Interrupt Triggered: Button Pressed!")
current_state = GPIO.input(LED_PIN)
GPIO.output(LED_PIN, not current_state) # Toggle LED
# 4. Attach Event Detection with Software Debouncing
GPIO.add_event_detect(
BUTTON_PIN,
GPIO.FALLING, # Detect transition from HIGH to LOW
callback=button_callback,
bouncetime=200 # Ignore bounces for 200 milliseconds
)
try:
print("System active. Press Ctrl+C to exit.")
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nShutting down safely...")
finally:
# 5. Mandatory Cleanup to reset pin states to floating inputs
GPIO.cleanup()
7.2 The gpiozero Library (High-Level Modern Paradigm)
Developed by the Raspberry Pi Foundation, gpiozero provides an object-oriented, expressive interface:
pythonfrom gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(27, bounce_time=0.2) # Defaults to pull-up active-low
# Declarative event binding
button.when_pressed = led.on
button.when_released = led.off
print("Running with gpiozero. Waiting for signals...")
pause()
7.3 Why GPIO.cleanup() is Mandatory
When a Python script terminates without executing GPIO.cleanup(), all pins configured as outputs remain driven in their last electrical state (e.g., driving 3.3V into an LED or relay coil). Running GPIO.cleanup() resets all used channels back to high-impedance input states, preventing short circuits when subsequent programs execute.