Raspberry PI Setup

Raspberry PI Setup
Author

Benedict Thekkel

Setup

1. Raspberry Pi 5 Overview and Features

  • Processor: Quad-core Cortex-A76 CPU at 2.4 GHz (upgraded for improved performance).
  • RAM: Available in configurations of 4GB or 8GB LPDDR4x, with faster memory than previous models.
  • Ports:
    • Dual micro-HDMI ports (4K output on each port).
    • USB 3.0 and USB 2.0 ports for faster data transfer.
    • Gigabit Ethernet and dual USB-C ports (one for power, one for peripherals).
    • M.2 PCIe slot (new) for connecting NVMe SSD storage.
  • Operating System: Raspberry Pi OS (based on Debian), but supports other OS options, including Ubuntu.

2. Initial Setup Requirements

  • Raspberry Pi 5 board (8GB model).
  • MicroSD card (minimum 16GB recommended) or an M.2 SSD if using NVMe storage.
  • Power supply: USB-C 5V/5A recommended for stable operation.
  • Micro-HDMI cable to connect to a display.
  • Keyboard and mouse (USB or Bluetooth).
  • Internet connection (Ethernet or WiFi).

3. Installing Raspberry Pi OS on the Raspberry Pi 5

Step 1: Download Raspberry Pi Imager

  • Download the Raspberry Pi Imager software from the Raspberry Pi website.
  • Insert your microSD card or connect your NVMe SSD (if using an M.2 to USB adapter) to your computer.

Step 2: Flash Raspberry Pi OS

  • Open Raspberry Pi Imager and select Raspberry Pi OS (32-bit or 64-bit depending on your needs).
  • Go to Edit Settings and add ssh key to laptop so you can ssh into it after boot
  • Check Wifi settings
  • Choose your storage device (microSD card or external drive).
  • Click Write to start the flashing process.

Step 3: Insert the microSD Card or SSD into Raspberry Pi

  • Once flashing is complete, insert the microSD card into the Raspberry Pi 5’s card slot or connect the SSD to the M.2 slot.
  • Connect the keyboard, mouse, display, and power supply to the Pi.

4. First Boot and Configuration

  • Power On: Turn on the Raspberry Pi by plugging it in. It should boot directly to Raspberry Pi OS.
  • Initial Setup Wizard: The setup wizard will guide you through setting up basic configurations:
    • Language and Location: Select your region, language, and keyboard layout.
    • Network: Connect to WiFi (if not using Ethernet).
    • Update OS: Let the system check for updates and install any available.
  • Enable SSH and VNC (Optional): To control your Pi remotely, enable SSH and VNC:
    • Go to Preferences > Raspberry Pi Configuration > Interfaces.
    • Enable SSH for remote command-line access, and VNC for remote desktop access.

5. Configuring Storage Options

If you plan to use an M.2 NVMe SSD, configure the Raspberry Pi to boot from the SSD instead of the microSD card.

Steps to Boot from SSD:

  • Insert both the microSD card (with the OS installed) and the SSD into the Raspberry Pi.
  • Open a terminal and update the bootloader: bash sudo apt update sudo apt full-upgrade
  • Use the Raspberry Pi Configuration tool or raspi-config to set the boot priority to USB or SSD.

6. Connecting GPIO Accessories

The GPIO pins on the Raspberry Pi 5 allow you to connect external devices like sensors, LEDs, motors, and HATs. You can control these peripherals using Python libraries like RPi.GPIO or gpiozero.

Example code to control an LED:

import gpiozero

led = gpiozero.LED(17)  # Connect LED to GPIO pin 17
led.on()

7. Installing Essential Software and Tools

  • Python Libraries: Raspberry Pi OS comes with Python pre-installed, but you can add popular libraries: bash sudo apt install python3-pip pip3 install gpiozero RPi.GPIO
  • Web Servers: If using the Pi for web development, install Apache or NGINX: bash sudo apt install apache2
  • Databases: Install SQLite, MySQL, or PostgreSQL if you need a database. bash sudo apt install sqlite3

8. Using the Pi as a Desktop PC

With its increased power, the Raspberry Pi 5 (8GB RAM) can function as a modest desktop computer for web browsing, coding, and office tasks: - LibreOffice: Comes pre-installed for document editing. - Web Browser: Chromium is pre-installed, and other browsers like Firefox can be added. - Code Editors: Editors like VS Code or Thonny are popular for coding on the Raspberry Pi.

10. Maintaining and Updating the Pi

  • Regular Updates: Keep the OS and software up to date for security and performance. bash sudo apt update && sudo apt upgrade -y
  • Backups: Use tools like rsync to back up data to an external drive or cloud storage.

VNC

Install tigervnc

sudo apt install tigervnc-standalone-server tigervnc-viewer -y

Add .files git

bpytop

sudo apt install software-properties-common
sudo apt install bpytop

Program GPIO Pins

The Raspberry Pi 5’s GPIO pins allow for various types of hardware control and communication, enabling you to interface with LEDs, sensors, motors, displays, and more. The main GPIO protocols on the Pi include digital I/O, PWM, I2C, SPI, UART, and 1-Wire. Python makes it easy to work with these protocols, especially using libraries like RPi.GPIO, gpiozero, and spidev.

1. Setting Up GPIO on Raspberry Pi

  • RPi.GPIO: A popular library for low-level control of the GPIO pins. bash sudo apt update sudo apt install python3-rpi.gpio
  • gpiozero: A higher-level, beginner-friendly library for common hardware components. bash sudo apt install python3-gpiozero

2. Configuring GPIO Pins

GPIO pins can be configured as either input or output. RPi.GPIO uses two main numbering systems: - BCM (Broadcom): The GPIO pin numbers as per the Broadcom chip. - BOARD: Physical pin numbers on the board header.

3. Basic Digital I/O (Input and Output)

Output Example (LED Blinking)

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)  # Use GPIO pin 17

try:
    while True:
        GPIO.output(17, GPIO.HIGH)  # Turn LED on
        time.sleep(1)
        GPIO.output(17, GPIO.LOW)   # Turn LED off
        time.sleep(1)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

Input Example (Button)

GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Use GPIO 18 with a pull-up resistor

while True:
    if GPIO.input(18) == GPIO.LOW:  # Button pressed
        print("Button Pressed!")
    time.sleep(0.1)

4. Pulse Width Modulation (PWM)

PWM is used to control things like LED brightness and motor speed by adjusting the duty cycle.

PWM Example

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)

pwm = GPIO.PWM(17, 1000)  # Initialize PWM on pin 17 at 1 kHz frequency
pwm.start(0)              # Start with 0% duty cycle (off)

try:
    for duty_cycle in range(0, 101, 5):
        pwm.ChangeDutyCycle(duty_cycle)
        time.sleep(0.1)
finally:
    pwm.stop()
    GPIO.cleanup()

5. I2C Communication (Inter-Integrated Circuit)

I2C is commonly used for sensors, displays, and EEPROMs. The Raspberry Pi 5’s default I2C pins are SDA1 (GPIO 2) and SCL1 (GPIO 3).

Enable I2C and Install smbus Library

sudo apt install -y i2c-tools python3-smbus

Scanning for I2C Devices

i2cdetect -y 1

I2C Example (Reading a Sensor)

import smbus
import time

bus = smbus.SMBus(1)       # Use I2C bus 1
DEVICE_ADDRESS = 0x48      # Replace with the I2C address of your device
REGISTER = 0x00            # Register to read from

while True:
    data = bus.read_byte_data(DEVICE_ADDRESS, REGISTER)
    print("Data:", data)
    time.sleep(1)

6. SPI Communication (Serial Peripheral Interface)

SPI is often used for displays, SD cards, and other high-speed peripherals. The default SPI pins on the Raspberry Pi 5 are MOSI (GPIO 10), MISO (GPIO 9), SCK (GPIO 11), and CE0 (GPIO 8).

Enable SPI and Install spidev

sudo apt install python3-spidev

SPI Example

import spidev
import time

spi = spidev.SpiDev()
spi.open(0, 0)            # Open SPI bus 0, chip select 0
spi.max_speed_hz = 50000  # Set the maximum speed

try:
    while True:
        resp = spi.xfer2([0xAA])  # Send data (0xAA is an example byte)
        print("Response:", resp)
        time.sleep(1)
finally:
    spi.close()

7. UART Communication (Universal Asynchronous Receiver-Transmitter)

UART is used for serial communication, such as GPS modules or serial displays. The default UART pins are TX (GPIO 14) and RX (GPIO 15).

Enable UART and Install pyserial

sudo apt install python3-serial

UART Example

import serial
import time

ser = serial.Serial("/dev/serial0", baudrate=9600, timeout=1)  # Open UART on /dev/serial0

try:
    ser.write(b"Hello from Raspberry Pi 5\n")  # Write data
    while True:
        if ser.in_waiting > 0:
            data = ser.readline().decode().strip()
            print("Received:", data)
finally:
    ser.close()

8. 1-Wire Communication

1-Wire is often used for temperature sensors like the DS18B20. The default 1-Wire GPIO pin is GPIO 4.

Enable 1-Wire

  1. Open the configuration:

    sudo raspi-config
  2. Go to Interface Options > 1-Wire and enable it. Reboot if prompted.

Read 1-Wire Data (Example for DS18B20 Sensor)

  1. Find the sensor in /sys/bus/w1/devices/.

  2. Read the sensor data:

    import os
    import time
    
    sensor_path = '/sys/bus/w1/devices/28-XXXXXXXXXXXX/w1_slave'  # Replace with your sensor’s address
    
    def read_temp():
        with open(sensor_path, 'r') as f:
            lines = f.readlines()
        if "YES" in lines[0]:
            temp_str = lines[1].split("t=")[1]
            temp_c = float(temp_str) / 1000.0
            return temp_c
    
    while True:
        temp = read_temp()
        print("Temperature:", temp, "°C")
        time.sleep(1)

9. Using the gpiozero Library for High-Level Control

gpiozero offers an easier, high-level approach for beginners and comes with built-in support for LEDs, buttons, motors, and more.

LED and Button with gpiozero

from gpiozero import LED, Button
from signal import pause

led = LED(17)
button = Button(18)

button.when_pressed = led.on
button.when_released = led.off

pause()  # Keep the program running

10. Example: Combining Multiple Protocols

This example combines GPIO, PWM, and I2C to control an LED and read sensor data:

from gpiozero import LED, PWMLED
from smbus import SMBus
import time

# Initialize an LED on GPIO 17 and an I2C sensor on address 0x48
led = LED(17)
pwm_led = PWMLED(17)
bus = SMBus(1)
DEVICE_ADDRESS = 0x48
REGISTER = 0x00

# Toggle the LED and adjust PWM based on sensor data
try:
    while True:
        data = bus.read_byte_data(DEVICE_ADDRESS, REGISTER)
        brightness = data / 255  # Scale to 0.0 - 1.0 for PWM
        pwm_led.value = brightness
        time.sleep(0.1)
except KeyboardInterrupt:
    pass

Summary of Raspberry Pi 5 GPIO Communication Protocols

Protocol Pins Libraries Common Devices
Digital I/O Any GPIO RPi.GPIO, gpiozero Buttons, LEDs, Relays
PWM Any GPIO RPi.GPIO, gpiozero LEDs (dimming), motors
I2C SDA (GPIO 2), SCL (GPIO 3) smbus, gpiozero Sensors, displays
SPI MOSI (GPIO 10), MISO (GPIO 9), SCK (GPIO 11), CE0 (GPIO 8) spidev, gpiozero SD cards, displays
UART TX (GPIO 14), RX (GPIO 15) serial, gpiozero GPS, serial displays
1-Wire GPIO 4 os, gpiozero DS18B20 temperature sensor

Tips for GPIO Programming

  • Use Pull-up/Pull-down Resistors: Ensure stability with pull-up or pull-down resistors for inputs.
  • Error Handling: Use try...except to handle unexpected interruptions.
  • Cleanup: Always call GPIO.cleanup() to reset pins after running scripts with RPi.GPIO.

This guide covers the essentials of each protocol, providing a foundation for more advanced projects with the Raspberry Pi 5 and Python GPIO programming.

Back to top