Unit 1: Setting Up and GPIO Handling

ECE140 — Workshop On Iot For Digital Society 9 min read

I. Raspberry Pi Foundations

The Raspberry Pi is a compact single-board computer developed by the Raspberry Pi Foundation (first released in 2012). It combines a processor, memory, peripheral interfaces, networking, and general-purpose input/output pins, enabling it to function as both a Linux computer and an embedded Internet of Things controller.

A. Introduction to Raspberry Pi

The Raspberry Pi provides the computing, communication, and physical interfacing capabilities needed to build IoT systems.

  • Core components:
    • System-on-Chip: Integrates an ARM processor, graphics processor, and peripheral controllers.
    • RAM: Stores programs and active data; capacity depends on the model.
    • Storage: Raspberry Pi OS is usually stored on a microSD card, although many models also support USB storage.
  • Connectivity: Depending on the model, interfaces include Ethernet, Wi-Fi, Bluetooth, USB, HDMI, camera, display, and audio facilities.
  • GPIO capability: The 40-pin header connects LEDs, switches, sensors, motors, displays, and communication modules to software.
  • Operating principle: Linux applications read inputs, process data, control outputs, and communicate with remote services.
  • IoT role:
    • Device node: Collects sensor data and controls actuators.
    • Edge computer: Processes data locally before transmission.
    • Gateway: Connects local devices to cloud or network services.
  • Important distinction: A Raspberry Pi is a full computer running an operating system, whereas a typical microcontroller executes firmware directly with more deterministic timing.

II. Raspberry Pi OS Installation and Maintenance

Raspberry Pi OS is a Debian-based operating system optimized for Raspberry Pi hardware. Initial preparation involves writing an operating-system image to storage, configuring startup options, and updating installed software.

A. Downloading the Raspberry Pi Imager

Raspberry Pi Imager is the official utility for selecting, configuring, and writing an operating-system image to a microSD card or USB storage device.

  • Download source: Obtain Raspberry Pi Imager from the official Raspberry Pi software website for Windows, macOS, or Linux.
  • Required items: A Raspberry Pi, compatible power supply, microSD card—typically 16 GB or larger—and a card reader are needed.
  • Imaging sequence:
    1. Insert the microSD card into the computer.
    2. Open Raspberry Pi Imager.
    3. Select the Raspberry Pi model.
    4. Choose Raspberry Pi OS.
    5. Select the target storage device.
    6. Apply customization settings and begin writing.
  • Customization options: The Imager can preconfigure hostname, username, password, Wi-Fi credentials, keyboard layout, time zone, and SSH access.
  • Data protection: Writing an image erases the selected storage device; the device name and capacity must be checked carefully.
  • Verification: Imager normally verifies written data after imaging, reducing failures caused by corrupt downloads or defective storage.

B. Setting and updating the Raspberry Pi OS

Correct first-boot configuration and regular package updates improve security, compatibility, and system reliability.

  • First boot: Insert the prepared card, connect required peripherals, and power the board using a suitable regulated supply.
  • System configuration: The graphical setup wizard or raspi-config can configure locale, interfaces, display behavior, and login options.
BASH
sudo raspi-config
  • Package index update: This downloads the latest package metadata without installing packages.
BASH
sudo apt update
  • Software upgrade: This installs available compatible package upgrades.
BASH
sudo apt full-upgrade
  • Restart: Reboot after major kernel, firmware, interface, or desktop changes.
BASH
sudo reboot
  • Security practice: Use a strong password, install updates regularly, and avoid exposing SSH or VNC directly to the public Internet.
  • Power discipline: Shut down before disconnecting power to reduce filesystem corruption.
BASH
sudo shutdown -h now

III. Remote Graphical Access

Remote desktop software allows a Raspberry Pi desktop to be viewed and controlled from another computer, which is useful for headless or remotely installed IoT nodes.

A. Installing RealVNC

RealVNC uses the Virtual Network Computing protocol to transmit the graphical desktop and return keyboard and mouse input.

  • Server and Viewer:
    1. VNC Server: Runs on the Raspberry Pi and shares its desktop.
    2. VNC Viewer: Runs on the controlling computer or mobile device.
  • Server installation: On Raspberry Pi OS versions supporting the RealVNC package, install it from the configured repository.
BASH
sudo apt update
sudo apt install realvnc-vnc-server
  • Enabling access: Where RealVNC Server is supported, open raspi-config, select interface options, and enable VNC.
  • Client connection: Install RealVNC Viewer on the client and connect using the Pi’s hostname or IP address.
  • Address discovery:
BASH
hostname -I
  • Version consideration: Newer Raspberry Pi OS releases using Wayland may provide WayVNC rather than RealVNC Server by default. RealVNC Server may require a supported desktop configuration, such as an X11 session.
  • Network security: Prefer a trusted local network or VPN; authentication credentials must not be shared or left at defaults.

IV. GPIO Architecture and Pin Functions

GPIO pins form the electrical interface between Raspberry Pi software and external circuits. They can provide digital input, digital output, and alternate hardware functions.

A. Pin configuration of Raspberry Pi

Pin configuration requires distinguishing physical header positions from Broadcom GPIO numbering.

  • Header arrangement: Most current boards expose a 40-pin header containing GPIO, power, ground, and reserved pins.
  • Numbering conventions:
    1. BOARD numbering: Uses physical positions, such as physical pin 11.
    2. BCM numbering: Uses the processor signal name; physical pin 11 is GPIO17.
  • Software convention: GPIO Zero normally uses BCM numbers, so LED(17) means GPIO17, not physical pin 17.
  • Mode configuration: A GPIO may be configured as input, output, or an alternate function such as I²C, SPI, UART, or PWM.
  • Pin inspection: The pinout command displays a model-appropriate header diagram.
BASH
pinout
  • Connection rule: Wiring must be completed with power removed, and every external circuit must share a common ground with the Raspberry Pi.

B. Understanding GPIO header pin functions

The header contains several pin categories, each with a different electrical or communication purpose.

  • Power pins:
    • 3.3 V: Supplies low-voltage components compatible with the Pi.
    • 5 V: Connected to the system’s 5 V rail and must never be applied directly to a GPIO.
  • Ground pins: Provide the common 0 V reference required for signal measurement and current return.
  • Digital GPIO: Represent logical LOW near 0 V and logical HIGH near 3.3 V.
  • I²C functions: GPIO2 and GPIO3 commonly serve as SDA and SCL for addressed two-wire peripherals.
  • UART functions: GPIO14 and GPIO15 commonly provide serial transmit and receive signals.
  • SPI functions: Pins may provide clock, data-in, data-out, and chip-select signals for high-speed synchronous devices.
  • PWM functions: Selected GPIO pins can produce hardware-timed pulse signals; software PWM is also available on general outputs.
  • Reserved identification pins: GPIO0 and GPIO1 are associated with HAT identification and should normally remain undisturbed.

C. GPIO electrical characteristics and protection

GPIO protection is essential because the pins operate at 3.3 V and connect closely to the processor.

  • Voltage limit: GPIO inputs are not 5 V tolerant; applying 5 V can permanently damage the board.
  • Output current: GPIO pins are intended for logic-level signals, not for directly powering motors, relays, or high-current lamps.
  • LED resistor: A series resistor limits current according to Ohm’s law:
TEXT
R = (VGPIO − VF) / I
  • Symbol definitions: R is resistance in ohms, VGPIO is approximately 3.3 V, VF is LED forward voltage, and I is desired current in amperes.
  • Concrete example: For VF = 2.0 V and I = 0.005 A, R = 260 Ω; a standard 330 Ω resistor provides a conservative current.
  • Protection methods: Use transistor or MOSFET drivers, flyback diodes across inductive loads, voltage dividers or level shifters for higher-voltage signals, and decoupling capacitors where needed.
  • Floating-input prevention: Internal or external pull-up and pull-down resistors give disconnected inputs a defined logic level.
  • Static protection: Handle the board on a non-conductive surface and avoid touching header pins unnecessarily.

V. Digital Input and Output Interfacing

Digital interfacing converts physical events into logical input states and converts program decisions into electrical output states.

A. Switch interfacing with Raspberry Pi

A switch provides a binary input by connecting a GPIO to a known voltage level when pressed or released.

  • Active-low circuit: Connect one switch terminal to a GPIO and the other to ground, then enable the GPIO’s internal pull-up resistor.
  • Logic states:
    • Released: Pull-up holds the input HIGH at approximately 3.3 V.
    • Pressed: The switch connects the input to ground, producing LOW.
  • GPIO Zero example:
PYTHON
from gpiozero import Button
from signal import pause

button = Button(27, pull_up=True)
button.when_pressed = lambda: print("Pressed")
button.when_released = lambda: print("Released")

pause()
  • Debouncing: Mechanical contacts may rapidly alternate during one press. GPIO Zero can suppress this using bounce_time, such as Button(27, bounce_time=0.05).
  • Safety rule: Never connect a switch directly between a GPIO output set HIGH and ground, because this creates a short-circuit condition.

B. First program: LED blinking

LED blinking demonstrates output configuration, timing, circuit wiring, and program-controlled state changes.

  • Circuit: Connect GPIO17 through a 330 Ω resistor to the LED anode; connect the cathode to ground.
  • Program:
PYTHON
from gpiozero import LED
from time import sleep

led = LED(17)

while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)
  • Operation: led.on() produces a HIGH output, led.off() produces LOW, and sleep(1) holds each state for one second.
  • Blink period: One complete cycle lasts 2 s, so frequency is f = 1/T = 0.5 Hz, where T is period and f is frequency.
  • Execution: Save as blink.py and run with python3 blink.py; terminate using Ctrl+C.

VI. Pulse-Width Modulation and Combined Control

PWM controls average power by repeatedly switching a digital output while varying the proportion of each cycle spent HIGH.

A. PWM concept and switch interfacing

PWM enables effects such as LED brightness control, while a switch can select or change the duty cycle.

  • Duty cycle: The percentage of one period for which the signal remains HIGH.
TEXT
Duty cycle (%) = (TON / T) × 100
  • Symbol definitions: TON is HIGH time and T is the complete PWM period; frequency is f = 1/T.
  • Practical meaning: A 25% duty cycle applies pulses for one-quarter of each cycle, giving an LED lower perceived brightness than a 75% duty cycle.
  • Combined program:
PYTHON
from gpiozero import PWMLED, Button
from signal import pause

led = PWMLED(18)
button = Button(27, pull_up=True)

button.when_pressed = lambda: setattr(led, "value", 1.0)
button.when_released = lambda: setattr(led, "value", 0.2)

pause()
  • Value range: PWMLED.value ranges from 0.0 for off to 1.0 for full duty cycle.
  • Limitations: PWM does not create a true analog voltage, and high-current devices still require an appropriate transistor or driver circuit.