Lecture 8 - Introduction to Raspberry Pi
Raspberry Pi — What Is It?
- A Raspberry Pi is not a microcontroller. It is a powerful Single-Board Computer (SBC) that serves a unique role in IoT systems.
- 1) A Bridge Between Software and Hardware
- It runs a full operating system (Linux), allowing for complex software development.
- It features GPIO pins to directly interface with sensors and actuators, just like a microcontroller.
- 2) Powerful Processing Capabilities
- It can run demanding applications that are too heavy for a typical microcontroller, such as:
- Web servers
- Databases
- Python scripts with complex libraries
- Machine learning models
- It can run demanding applications that are too heavy for a typical microcontroller, such as:
- 3) An Ideal IoT Gateway
- Its combination of robust networking (Wi-Fi, Ethernet), processing power, and the ability to run software like an MQTT broker makes it a perfect choice for a central hub or gateway in an IoT system.
Analogy
A microcontroller (like an ESP32/Arduino) is a reflex — fast, simple, does one job. A Raspberry Pi is a small brain — it can think (run Linux, databases, ML) and still has "hands" (GPIO pins) to touch the physical world. In an IoT system, it's often the manager that collects reports from many small workers (sensors/microcontrollers) and talks to the internet.
Outlines
- Hardware and Pins
- Raspberry Pi Setup
- Programming GPIO Pins using gpiozero Python Library
- Creating a Simple GUI using guizero Python Library
- Programming Raspberry Pi Towards IoT Applications Using Python
References
- Web Pages:
- Raspberry Pi 4 Layout: https://www.etechnophiles.com/raspberry-pi-4-gpio-pinout-specifications-and-schematic/
- Raspberry Pi 4 Pinout, Features and Peripherals: https://microcontrollerslab.com/raspberry-pi-4-pinout-description-features-peripherals-applications/
- gpiozero Library: https://gpiozero.readthedocs.io/en/stable/index.html#
- guizero Library: https://lawsie.github.io/guizero/
- Books:
- Chapters 12 – 18, 20 of "Raspberry Pi 4: The Ultimate Step-by-Step" by Liam Clark (2021).
- Chapter 4 of "Learn Electronics with Raspberry Pi," 2nd Ed., by Stewart Watkiss (2020).
- Chapters 10, 16 of "Raspberry Pi Cookbook," 3rd Ed., by Simon Monk (2019).
1. Hardware and Pins
Raspberry Pi 4 Hardware
- Raspberry Pi is a small-sized computer that uses the Linux operating system and has pins to connect with sensors and actuators.
- It is a mini-size computer used mostly to run larger and smarter programs to achieve output quickly.
[Image: Raspberry Pi 4 board layout — top view (labelled components) and bottom view (SD card slot)]
- Labelled components on the board (from the figure):
- 40-pin GPIO Header
- Broadcom BCM2711B0 (CPU)
- LPDDR4 SDRAM (2GB, 4GB, 8GB)
- Ethernet Controller
- PoE HAT Header
- Gigabit Ethernet port
- 2× USB 3.0
- 2× USB 2.0
- USB Controller
- 3.5 mm 4-pole Composite Audio-Video output
- CSI Camera port
- Micro HDMI ports ×2 (support up to 4K)
- 5V@3A USB-C Power port
- DSI Display Port
- Dual Band Wi-Fi (2.4GHz & 5GHz) and Bluetooth 5.0
- SD Card Slot (on the bottom side)
Hardware Specifications
- CPU: Broadcom BCM2711 chip containing a 1.5GHz 64-bit quad-core ARM processor (ARMv8-architecture core).
- The slide says Cortex-A53. Note: the Pi 4's BCM2711 actually uses Cortex-A72 cores (the A53 is in the Pi 3). Know what your lecturer wrote for the exam, but be aware of this.
- GPU: Broadcom VideoCore VI @ 500 MHz.
- Capable of Blu-ray quality video playback, H.265 (4Kp60 decode); H.264 (1080p60 decode, 1080p30 encode); OpenGL ES 3.0 graphics.
- RAM: Comes in 2GB, 4GB, and 8GB variants (depending on version) of LPDDR4 SDRAM.
- USB ports: Two USB 3.0 and two USB 2.0 ports to connect an external keyboard, mouse, or other peripheral devices.
- USB power port: A 5.1V, 3A USB Type-C power port.
- HDMI ports: Two micro HDMI ports supporting up to 4K@60Hz resolution.
- Ethernet port: True Gigabit Ethernet, capable of sending Ethernet frames at one gigabit per second:
- Composite Video Output: Both the audio output socket and the composite video socket reside in a single 4-pole 3.5mm socket.
- SD Card Slot: ⭐ A micro-SD card slot is used for booting up the operating system and for storage.
Analogy The
micro-SD card is the Pi's hard drive and its brain's memory of who it is. No SD card (or a broken one) = the computer has no OS to wake up into, like a laptop with its SSD removed.
40 Pins Overview
[Image: Raspberry Pi 4 board with the 40-pin GPIO header pinout diagram]
- 40 pins in total:
- 26 GPIO pins
- Two 5V pins
- Two 3V3 (3.3V) pins
- 7 ground pins (0V) (the next slide says 8 — see below)
- Other GPIO pins of the RPi 4 are capable of generating PWM output, and the board supports SPI, I2C, and UART serial communication protocols.
Raspberry Pi 4 Pins
- We connect input/output devices to Raspberry Pi pins. Below is a complete overview of all GPIOs and their primary functions.
- Each pin has a ⭐ physical pin number: 1, 2, 3, ….
- We have power supply pins (3.3V and 5V) and ground pins (0V).
- We have 26 pins to connect with input/output devices, i.e., the GPIO pins.
- ⭐ In our Python programs, we refer to a pin by its GPIO number, not its physical pin number.
Pinout Table
| GPIO / Power | Function | Pin | Pin | Function | GPIO / Power |
|---|---|---|---|---|---|
| 3V3 | 3V3 | 1 | 2 | 5V | 5V |
| GPIO2 | SPI3 MOSI / SDA3 | 3 | 4 | 5V | 5V |
| GPIO3 | SPI3 SCLK / SCL3 | 5 | 6 | GND | GND |
| GPIO4 | SPI4 CE0 N / SDA3 | 7 | 8 | TXD1 / SPI5 MOSI | GPIO14 |
| GND | GND | 9 | 10 | RXD1 / SPI5 SCLK | GPIO15 |
| GPIO17 | — | 11 | 12 | SPI6 CE0 N | GPIO18 |
| GPIO27 | SPI6 CE1 N | 13 | 14 | GND | GND |
| GPIO22 | SDA6 | 15 | 16 | SCL6 | GPIO23 |
| 3V3 | 3V3 | 17 | 18 | SPI3 CE1 N | GPIO24 |
| GPIO10 | SDA5 | 19 | 20 | GND | GND |
| GPIO9 | RXD4 / SCL4 | 21 | 22 | SPI4 CE1 N | GPIO25 |
| GPIO11 | SCL5 | 23 | 24 | SDA4 / TXD4 | GPIO8 |
| GND | GND | 25 | 26 | SCL4 / SPI4 SCLK | GPIO7 |
| GPIO0 | SPI3 CE0 N / TXD2 / SDA6 | 27 | 28 | SPI3 MISO / SCL6 / RXD2 | GPIO1 |
| GPIO5 | SPI4 MISO / RXD3 / SCL3 | 29 | 30 | GND | GND |
| GPIO6 | SPI4 MOSI / SDA4 | 31 | 32 | SDA5 / SPI5 CE0 N / TXD5 | GPIO12 |
| GPIO13 | SPI5 MISO / RXD5 / SCL5 | 33 | 34 | GND | GND |
| GPIO19 | SPI6 MISO | 35 | 36 | SPI1 CE2 N | GPIO16 |
| GPIO26 | SPI5 CE1 N | 37 | 38 | SPI6 MOSI | GPIO20 |
| GND | GND | 39 | 40 | SPI6 SCLK | GPIO21 |
- Legend (colour-coded in the slide): I2C, UART, SPI, Ground, 5V Power, 3V3 Power.
Analogy
Physical pin number = the seat number in a cinema row (1, 2, 3… by position). GPIO (BCM) number = the person's name sitting in that seat. Python calls people by name, not seat. So LED(22)means "GPIO22" — which actually sits at physical pin 15.
Pin Rules & Notes
- ⭐ Referring to a pin by its GPIO number is known as the BCM (Broadcom) numbering system, which will be used in our Python programs.
- Some pins have alternative functions (used for communications, e.g., I2C, SPI, …).
- Some references mention that Pins 27 and 28 are reserved (not used).
- There are 8 ground pins (GND).
- (Counting the table: pins 6, 9, 14, 20, 25, 30, 34, 39 = 8 GND pins. The earlier "7" figure is inconsistent — 8 is what the table shows.)
- ⭐ The GPIO pins of the Raspberry Pi 4 are all digital pins. They can be either input or output pins.
- Input voltage between 1.8V and 3.3V is read as HIGH. Input voltage lower than 1.8V is read as LOW.
- ⚠️ Do NOT connect an external device with an output voltage above 3.3V to any GPIO pin, or it will burn your Raspberry Pi board.
- Input voltage between 1.8V and 3.3V is read as HIGH. Input voltage lower than 1.8V is read as LOW.
- PWM (pulse-width modulation) pins:
- Software PWM is available on all pins.
- Hardware PWM is available on these pins only: GPIO12, GPIO13, GPIO18, GPIO19.
Analogy The GPIO pins are like
3.3V-rated pipes. Pushing 5V into them is like forcing high-pressure water into a thin garden hose — it bursts. Even though the board has 5V pins (for powering things), the GPIO "listening" pins can only take up to 3.3V.
Analogy — Software vs Hardware PWM
Hardware PWM = a dedicated metronome that ticks perfectly on its own. Software PWM = the CPU tapping its foot to keep the beat while also doing other work — it works, but can wobble if the CPU gets busy.
2. Raspberry Pi Setup
- ⚠️ Very Important:
- You will set up a couple of user names and passwords. Make sure you record all of them, since you will need them to access your Raspberry Pi again and again.
1. Raspberry Pi OS
- A Raspberry Pi needs an operating system, which must be installed on an SD card.
- In our course, you have been given an SD card with the Raspberry Pi OS.
- ⭐ You do not need to do the OS installation.
- Default credentials:
- Username:
pi - Password:
raspberry
- Username:
Installing Raspberry Pi OS (FYI)
- If you prefer to install the OS on the SD card yourself, feel free to do so:
- Install an OS on an SD card easily using the Raspberry Pi Imager, downloadable from: https://www.raspberrypi.org/software/
- By running the Raspberry Pi Imager, select an operating system and install it on the SD card. Demonstration video: https://www.youtube.com/watch?v=ntaXWS8Lk34
- In this course, we install "Raspberry Pi OS".
- Then, run your Raspberry Pi by inserting the SD card and powering it up.
2. Access Raspberry Pi via a Computer
- During class, to work on the Raspberry Pi, we might need to use a notebook computer's keyboard, mouse, and monitor to access the Raspberry Pi.
- We will access a Raspberry Pi via an Ethernet cable. Install the following software on your notebook:
- PuTTY — https://putty.org/index.html
- VNC Viewer — https://vnc-viewer.en.softonic.com/, www.realvnc.com
- These setup steps come from these references:
- https://beebom.com/how-use-windows-laptop-as-monitor-raspberry-pi/
- https://blackdevice.com/how-to-connect-to-raspberry-pi/#:~:text=Direct%20ethernet%20connection,%C2%BB%20menu%2C%20and%20click%20Ok
- https://raspberrypi-guide.github.io/networking/create-direct-ethernet-connection#:~:text=a%20Windows%20PC-,Direct%20connection%20with%20a%20Mac,without%20the%20ethernet%20cable%20again
Analogy
SSH (PuTTY) = talking to the Pi by text message — you type commands, it types back.VNC (VNC Viewer) = a video call with screen-share — you see and control the Pi's actual desktop. "Headless" Pi = a Pi with no monitor/keyboard of its own; you borrow your laptop's.
Step-by-Step Setup
- Power on your Raspberry Pi (with the SD card inside).
- Connect the cable: Use an Ethernet cable to connect the Raspberry Pi directly to your computer's Ethernet port, or to a USB-to-Ethernet adapter if your computer lacks one.
[Image: Photo of Raspberry Pi connected to a laptop via Ethernet cable and powered from a power strip]
- Share the internet connection:
- 3.1) On Windows:
- Go to "Settings" > "Network & Internet" > "Wi-Fi" and click "Change adapter options".
- Right-click your internet-connected adapter (e.g., Wi-Fi), go to "Properties" > "Sharing", and check the box "Allow other network users to connect".
- Under "Home networking connection", select the "Ethernet" connection to the Pi from the dropdown and click "OK".
- 3.1) On Windows:
[Image: Windows screenshots — Settings → Network & Internet → Wi-Fi → Change adapter options → Wi-Fi Properties → Sharing tab]
- 3.2) On macOS:
- Go to "System Preferences" > "Sharing".
- Select "Internet Sharing" from the list on the left.
- From the "Share your connection from" dropdown, select your internet source (like Wi-Fi). Below, check the box next to your wired network interface (e.g., USB 10/100/1000 LAN).
Analogy Internet sharing turns your laptop into a
mini router: Wi-Fi brings the internet into your laptop, and the Ethernet cable passes it along to the Pi — like sharing your phone's hotspot, but through a cable.
- Open PuTTY:
- Type
raspberrypi.localin the Host Name field. - Select "SSH" as the Connection type (Port 22).
- Click "Open" at the bottom.
- Remark:
- If you cannot access the Raspberry Pi via SSH, your Pi might be missing the file named
ssh. - You may need to create this file
sshon your Pi's SD card. - See Step 2 in: https://beebom.com/how-use-windows-laptop-as-monitor-raspberry-pi/
- If you cannot access the Raspberry Pi via SSH, your Pi might be missing the file named
- Type
[Image: PuTTY Configuration window with raspberrypi.local, Port 22, SSH selected, Open button highlighted]
- A console window opens. By default:
- Username:
pi - Password:
raspberry - Type these in the console and press Enter. You will log into the Raspberry Pi's console.
- Username:
[Image: PuTTY console showing "login as: pi" and password prompt]
- To configure the Raspberry Pi, type the command and press Enter:
sudo raspi-config[Image: PuTTY console running sudo raspi-config]
- This launches the configuration tool for Raspberry Pi.
- Move to "Interface Options" (or "Interfacing Options") using the keyboard's arrow keys.
- Press Enter.
[Image: raspi-config main menu with "3 Interface Options" highlighted]
- Under Interface Options, move to "VNC" and press Enter.
- On the next page, choose "Yes" and press Enter (enables the VNC Server).
[Image: raspi-config Interface Options list (P3 VNC highlighted) and "Would you like the VNC Server to be enabled?" dialog]
- Open "System Options".
- Go to "Boot / Auto Login".
- Move to the "Desktop Autologin" option.
- (On an old Raspberry Pi, navigate to Boot Options → Desktop/CLI → Desktop Autologin.)
- Select the Ok button.
[Image: raspi-config System Options and Boot/Auto Login menu with "B4 Desktop Autologin" highlighted]
- Move to "Finish" by pressing Tab and Enter. The Raspberry Pi will reboot, and the SSH session ends. Close PuTTY and other windows.
[Image: raspi-config main menu with Finish highlighted]
- Run/open VNC Viewer. Enter
raspberrypi.localand press Enter. - A prompt appears — click "Continue". In the next window, enter your RPi's credentials:
- Username:
pi - Password:
raspberry - Click "OK".
- Username:
[Image: VNC Viewer address bar with raspberrypi.local, and VNC Authentication dialog]
- The Raspberry Pi's screen will be live on your laptop's display. Go through the on-screen instructions to set up the Raspberry Pi.
[Image: Raspberry Pi desktop shown inside VNC Viewer on a Windows laptop]
Setup flow in one line Power on → Ethernet cable → share internet →
SSH in (PuTTY) → sudo raspi-config → enable VNC + Desktop Autologin → Finish/reboot → connect with VNC Viewer → see the Pi desktop.
- Remark:
- You can also access a Raspberry Pi via a Wi-Fi access point (Wi-Fi communication).
- You might need to choose an access point that you can use during classes and the exam (e.g., a mobile phone as an access point).
- Videos demonstrating the setup (some for macOS, some for Windows): https://www.youtube.com/results?search_query=raspberry+pi+headless+install
3. Programming GPIO Pins Using gpiozero Python Library
- Writing Python programs (run on a Raspberry Pi) to read inputs from switches and control LEDs, where these switches and LEDs connect to the Raspberry Pi's pins.
1. Access GPIO Pins using Python
1.1 Introduction
- In this section, we start unlocking the real power of the Raspberry Pi — the GPIO pins, or General Purpose Input Output pins.
- The GPIO allows you to connect your Raspberry Pi to the outside world (input/output (I/O) devices) through pins that may be set to input or output, and are controlled through code.
- We will connect I/O devices (sensors/actuators) and write Python programs to interact with them via GPIO pins.
- ⭐ Specifically, we will use LEDs and switches in our examples.
- Since all Raspberry Pi GPIO pins are digital, reading analog-input values requires an analog-to-digital converter (ADC) chip (which we do not have). Therefore, we will not use potentiometers here.
Analogy A digital pin is a
light switch: it only knows ON or OFF. A potentiometer is a dimmer knobwith infinitely many positions. To read a dimmer with a light-switch reader, you need a translator — the ADC— which converts "how far the knob is turned" into numbers.
1.2 Thonny Python IDE
- We will use the Thonny Python IDE to write our Python programs.
- Thonny is included in Raspberry Pi OS. Launch it from the start menu under Programming → Thonny Python IDE.
[Image: Raspberry Pi start menu → Programming → Thonny Python IDE (via VNC Viewer)]
- The figure shows Thonny with the classic Hello World program, with output at the bottom (Shell).
- To run a Python program, click the Run button on the menu.
- The Python version shown is 3.7.3.
print("Hello World")[Image: Thonny IDE running Hello.py with "Hello World" output in the Shell]
1.3 GPIO Python Libraries
- To interact with GPIO pins, we need to import GPIO libraries into our Python programs. Several are pre-installed in Raspberry Pi OS:
- RPi.GPIO: A lower-level GPIO library with built-in functions used to control and access GPIO pins directly (similar to Arduino commands). Its functions are not aware of (do not depend on) which I/O devices are attached.
- PiGPIO: A lower-level GPIO library.
- ⭐ GPIOZero: A high-level GPIO library. Its built-in functions are defined for most commonly used devices, e.g., LED, switch, ultrasonic sensor, etc. Functions depend on the device attached; for a defined device, we can call its functions and interact with it easily.
- We will use this library in this course.
Analogy
RPi.GPIO = driving a manual car: you control the clutch and gears (set mode, set pin direction, write HIGH/LOW). GPIOZero = driving an automatic car: you just say "LED, turn on" and it handles the details.
1.4 Code Comparison
- Assume an LED is connected to GPIO18. We want to turn the LED on for 5 seconds, then off.
RPi.GPIO Library
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)
time.sleep(5)
GPIO.output(18, GPIO.LOW)GPIOZero Library ⭐
from gpiozero import LED # (slide has a typo: "gipozero")
import time
led = LED(18)
led.on()
time.sleep(5)
led.off()- Notice: GPIOZero needs no
setmodeand nosetup— creatingLED(18)handles both (BCM numbering is the default).
2. GPIOZero Library
2.1 Introduction
-
The GPIOZero Python library provides a simple interface to devices and sensors connected and controlled via GPIO pins.
-
⭐ The key feature of GPIOZero is to provide a high-level model or interface for devices commonly used with the Raspberry Pi.
- Unlike other libraries, it does not require the programmer to manage individual pins, but provides an interface and a set of high-level methods specific to each supported component.
-
The components (classes) supported include LED, button, motor, motion sensor, etc. Full list: https://gpiozero.readthedocs.io/en/stable/index.html
-
⭐ In each class, a set of built-in functions (methods) is provided.
- For example,
leddefined as the LED class can be commanded easily by built-in methods:led.on()andled.off()turn the LED on and off.led.blink()makes the LED turn on and off alternately.
- For example,
-
In this lecture, we experiment on 3 classes:
| Class | Device | Usage |
|---|---|---|
LED class | LED | To turn an LED on/off |
PWMLED class | LED | To control the intensity of an LED |
Button class | Button | To read the state (pressed/not pressed) of a button |
Analogy A
class is a blueprint/remote-control design ("LED remote" has on/off/blink buttons). Creating led = LED(22) is building one actual remote and pairing it with the LED on GPIO22. The methods are the buttons on that remote.
3. LED Class
3.1 Introduction
- GPIOZero provides a class called
LEDand its methods so we can control an LED easily.
1) Import the class at the beginning of your program:
from gpiozero import LED2) Declare that the (physical) LED connected to GPIO pinNum is an LED object called led:
led = LED(pinNum, active_high=True, initial_value=False, pin_factory=None)pinNum: Mandatory, integer — the pin number in BCM numbering to which the LED is connected.active_high: Optional Boolean (defaultTrue) — how the LED is wired to the GPIO.Truemeans the LED is connected so that supplying 3.3V at that pin turns the LED on.
initial_value: Optional Boolean (defaultFalse) — the initial state of the LED (off by default).pin_factory: Optional, advanced use only — specifies a GPIO pin factory different from GPIOZero's default.- ⭐ The last three can be omitted →
led = LED(22).
Analogy —
active_high active_high=True: LED goes from pin → GND, so pin HIGH = LED on(normal light switch). active_high=False: LED goes from 3.3V → pin, so pin LOW = LED on (an "upside-down" switch). The flag tells GPIOZero which way your switch is installed so on() always means on.
3) Main methods of the LED class:
| Method | Meaning |
|---|---|
on() | Turn the LED on |
off() | Turn the LED off |
toggle() | Reverses the LED state: if on → off; if off → on |
blink(on_time=1, off_time=1, n=None, background=True) | Makes the LED blink repeatedly |
- Usage:
led.on()
led.off()
led.toggle()
led.blink(on_time=2, off_time=1)blink()parameters:on_time: Optional, float (default1) — number of seconds the LED is on.off_time: Optional, float (default1) — number of seconds the LED is off.n: Optional, integer (defaultNone) — number of blinks. By default, the LED blinks infinitely.background: Optional, Boolean (defaultTrue) — whether the method returns immediately to the main flow or is blocking. By default, it returns immediately.
- One blink period:
- \boxed{T_{\text{blink}} = \text{on_time} + \text{off_time}}
Analogy —
background background=True = you set a blinking Christmas light and walk away — it keeps blinking while you do other things. background=False = you stand there holding the switch flicking it yourself — you can't do anything else until you're done.
Example 1: To Turn an LED On/Off
-
Connect an LED to GPIO22 and a 330 Ω resistor to GND.
-
Write a Python program using
on()andoff()to turn the LED on and off every 2 seconds, repeatedly. -
Circuit:
GPIO22 → LED → 330 Ω → GND
[Image: Circuit schematic (GPIO22 → LED → 330Ω → GND) and breadboard photo]
- Write the following in Thonny and click Run:
from gpiozero import LED
from time import sleep
LED_PIN = 22
led = LED(LED_PIN)
while True:
print ("on")
led.on()
sleep(2)
print ("off")
led.off()
sleep(2)- A demonstration video is shown on the slide.
[Image: Demo video screenshot — Thonny running LED_OnOff.py via VNC Viewer]
Why the 330 Ω resistor? An LED is like a
thirsty sponge for current — without a resistor it would gulp too much and burn out (or overload the pin). The resistor is a narrow straw that limits how fast current flows.
Example 2: To Blink an LED
- Using the same circuit, write the following and click Run:
from gpiozero import LED
LED_PIN = 22
led = LED(LED_PIN)
led.blink(on_time=2, off_time=4)- The LED is on for 2 s, off for 4 s, repeating forever → period s.
- A demonstration video is shown on the slide.
[Image: Demo video screenshot — Thonny running LED_Blink.py]
- Compare with Example 1: no
while Trueloop needed —blink()handles the repetition in the background.
4. PWMLED Class
4.1 Introduction
- ⭐ We can control the brightness/intensity of an LED using the
PWMLEDclass.
1) Import:
from gpiozero import PWMLED2) Define the (physical) LED connected to pin as a PWMLED object:
led = PWMLED(pin)pin: Mandatory, integer — the pin number in BCM numbering to which the LED is connected.
3) Set the "voltage supply" (brightness) to the pin:
led.value = VnumVnumis a float between 0 (off) and 1 (highest voltage).- Under the hood, PWM rapidly switches the pin on/off;
valueis the duty cycle (fraction of time the pin is HIGH). The effective average voltage is:
Analogy PWM is like
blinking your eyes extremely fast. If your eyes are open 50% of the time, the room seems half as bright. The pin is still only ON (3.3V) or OFF (0V) — it just flickers faster than your eye can notice, so the LED appears dimmer.
Example 3: Adjust LED Brightness
- Connect an LED to GPIO22 and a resistor as in the previous example.
- Write a program to receive an input value and adjust the LED intensity accordingly.
from gpiozero import PWMLED
led = PWMLED(22)
while True:
brightness_s = input("Enter Brightness (0.0 to 1.0):")
brightness = float(brightness_s)
led.value = brightnessinput()returns a string, so it must be converted withfloat()before assigning toled.value.- A demonstration video is shown on the slide.
[Image: Demo video screenshot — Thonny running LED_Brightness.py with input prompt in Shell]
5. Button Class
5.1 Introduction
- There are two possible button configurations, depending on the position of the resistor:
[Image: Pull-up schematic (VCC → R_PULLUP → GPIO → button → GND) and pull-down schematic (VCC → button → GPIO → R_PULLDOWN → GND)]
- a) Pull-Up: a resistor (10–100 kΩ) is inserted between the GPIO and the power supply (VCC).
- When the button is not pressed (OFF), the pin assumes a stable logic state 1 (HIGH).
- Unlike the case with no resistor, logic state 1 remains at the GPIO input in a stable and permanent way.
- Once the button is pressed, current flows to ground, bringing the pin to logic state 0 (LOW).
- b) Pull-Down: a resistor (10–100 kΩ) is inserted between the GPIO and ground (GND).
- With the button OFF (not pressed), the GPIO assumes a stable logic state 0 (LOW).
- Since the resistor is present, logic state 0 remains at the pin without oscillations.
- When the button is pressed, the pin is brought to logic state 1 (HIGH). (The slide says "current flows to the ground" — more precisely, pressing connects the pin to VCC, pulling it HIGH.)
| Configuration | Not pressed | Pressed |
|---|---|---|
| Pull-Up | HIGH (1) | LOW (0) |
| Pull-Down | LOW (0) | HIGH (1) |
Analogy Without a pull resistor, an input pin is a
flag in the wind ("floating") — it flaps randomly between HIGH and LOW. A pull-up is a spring holding a door open (HIGH); pressing the button pushes it shut (LOW). A pull-down is a spring holding the door shut (LOW); pressing the button pulls it open(HIGH).
- The
Buttonin GPIOZero belongs to the Input device class and is modeled by a simple, intuitive interface.
1) Import:
from gpiozero import Button2) Constructor syntax:
button = Button(pin, pull_up=True, bounce_time=None, hold_time=1,
hold_repeat=False, pin_factory=None)pin: Mandatory, integer — the pin number in BCM numbering to which the button is connected.pull_up: Optional Boolean — enables the internal Pull-Up (True, default) or Pull-Down (False) resistor.bounce_time: Optional float — avoids switch bounce by specifying the number of seconds during which changes in the button state are ignored. Disabled by default.hold_time: Optional float — duration in seconds the button must be held before thewhen_heldhandler is executed.hold_repeat: Optional Boolean — ifTrue, thewhen_heldhandler is called everyhold_timeseconds; ifFalse, it is called only once.- (Slide text says "True (Default)", but the constructor shows
hold_repeat=False— the actual default is False.)
- (Slide text says "True (Default)", but the constructor shows
pin_factory: Optional, advanced use only — specifies a GPIO pin factory different from GPIOZero's default.
Analogy —
bounce_time A mechanical button "bounces" like a dropped ball — one press can look like several rapid presses (on-off-on-off) for a few milliseconds. bounce_time says "ignore any extra bounces for X seconds after the first one."
Analogy — internal pull-up The Pi has
built-in pull resistors inside the chip. pull_up=True switches on the internal one, which is why the circuit in Example 4 needs no external resistor for the switch.
3) Main methods/properties of the Button class:
| Method | Meaning |
|---|---|
is_pressed | Returns True if the button is pressed |
wait_for_press(timeout=None) | Blocking call that waits for the button to be pressed or for the float-type timeout to expire |
wait_for_release(timeout=None) | Blocking call that waits for the button to be released or for the float-type timeout to expire |
when_held | Runs the associated function whenever the button is held down for hold_timeseconds |
when_pressed | Runs the associated function whenever the button is pressed |
when_released | Runs the associated function whenever the button is released |
- Usage example:
button.is_pressed
Analogy — polling vs events
is_pressed in a loop = checking your phone every second to see if someone messaged (polling). when_pressed = ... = turning on notifications — the phone tells you when a message arrives (event-driven / callback).
Example 4: To Turn an LED On/Off by a Switch (1)
-
Connect an LED to GPIO22 and a resistor (the LED circuit as before).
-
Connect a switch to GPIO18 (pull-up configuration — no resistor is needed, the internal pull-up is used).
-
Write a program such that pressing the switch turns the LED on; otherwise, the LED is off.
-
Circuit:
GPIO22 → LED → 330 Ω → GNDGPIO18 → SW → GND- If not pressed → SW is open.
- If pressed → SW is closed (GPIO18 pulled to GND → LOW →
is_pressed = True).
[Image: Circuit schematic with switch on GPIO18 to GND and LED on GPIO22, plus breadboard photo]
- In this example, we use the
is_pressedproperty (returnsTruewhen we press the switch):
from gpiozero import Button, LED
button = Button(18, pull_up=True)
led = LED(22)
while True:
if button.is_pressed:
led.on()
else:
led.off()- A demonstration video is shown on the slide.
[Image: Demo video screenshot — Thonny running Button_Pressed.py]
- Note: with
pull_up=True, the pin reads LOW when pressed, but GPIOZero automatically inverts this sois_pressedis stillTruewhen pressed.
Example 5: To Turn an LED On/Off by a Switch (2)
- Connect a switch and an LED to the Raspberry Pi as shown previously.
- In this example, we use:
when_pressed— runs the function on the right-hand side of=when we press the switch.when_released— runs the function on the right-hand side of=when we release the switch. (Slide says "press" — it means release.)
from gpiozero import Button, LED
button = Button(18, pull_up=True)
led = LED(22)
button.when_pressed = led.on
button.when_released = led.off- ⚠️ Note:
led.on— no parentheses! We pass the function itself, not call it. (led.on()would run it immediately and assign its return value,None.) - The result is similar to the previous example, but without a
while Trueloop.
Analogy
button.when_pressed = led.on is like giving someone your phone number ("call this when it happens"). Writing led.on() instead would be calling them right now — and handing over the result of the call, not the number.
4. Creating a Simple GUI using guizero Python Library
- Writing Python programs (run on a Raspberry Pi) to create simple GUIs and control LEDs, where these LEDs connect to the Raspberry Pi's pins.
1. Introduction
- ⭐ guizero is a Python 3 library for creating simple GUIs.
- It is designed to allow new learners to quickly and easily create GUIs for their programs.
- It provides many built-in functions to create different kinds of widgets (such as button, slider, etc.).
- List of available widgets: https://lawsie.github.io/guizero/widgetoverview/
[Image: Examples of guizero widgets — Button, Slider, radio buttons (cheese/ham/salad), Box with border, CheckBox, Text "Hello World"]
Analogy
gpiozero gives you a remote control for physical things (LEDs, buttons). guizero gives you on-screen buttons and sliders. Connect them, and the on-screen button becomes a remote control for the real LED.
2. Install the guizero Library
- Before using it, install guizero:
- Open a terminal window: Menu > Accessories > Terminal.
- Type this command and press Enter:
sudo pip3 install guizero- Or, if there is an error, use this instead:
sudo apt install python3-guizero- Or follow the suggestion provided in the Terminal.
[Image: Raspberry Pi menu → Accessories → Terminal]
3. Code Examples of using the guizero Library
1) App Object
- The App object is the basis of all GUIs created with guizero.
- ⭐ It is the main window which contains all of the other widgets.
- Create an App object:
app = App()appis the variable name of the App object.- Display the window:
app.display()- Example:
from guizero import App
app = App()
app.display()[Image: Empty guizero window titled "guizero"]
app.display()should be the last line — it starts the GUI's event loop and keeps the window open.
Analogy
App() is the empty picture frame / canvas; every widget is something you pin onto it. app.display() hangs the frame on the wall and keeps watching for clicks.
2) Slider Object
- The Slider object displays a bar and selector used to specify a value in the range 0–100.
slider = Slider(app, command=NameOfFunction)slideris the variable name of the Slider object;appis the variable name of the App object.NameOfFunctionis a custom function to run when we slide the slider bar.
[Image: guizero window with a slider at 57 and a text box showing 57]
3) Text Box Object
- The TextBox object creates a text box and displays a value inside.
textbox = TextBox(app)textboxis the variable name of the TextBox object.appis the variable name of the App object.- To specify the value shown in the text box:
textbox.value = ValueToBeShownValueToBeShownis the value we want to display in the text box.
[Image: guizero window with a slider at 57 and a text box showing 57]
Example: Slider and Text Box
- The code below will ⭐ create a Slider object and a Text Box object.
- Objective: The current value of the Slider (between 0 and 100) is displayed in the Text Box. We change the Slider's value by moving the Slider button.
from guizero import App, Slider, TextBox
def slider_changed(slider_value):
textbox.value = slider_value
app = App()
slider = Slider(app, command=slider_changed)
textbox = TextBox(app)
app.display()[Image: Resulting GUI window — slider at 57, text box shows 57]
- We write a custom function
slider_changed(slider_value)to be called every time we change the Slider's value. - The Slider's value is automatically passed to the input argument
slider_valueofslider_changed.
Analogy The slider is a
reporter: every time it moves, it phones slider_changed and reads out the new number (slider_value). The function then writes that number onto the whiteboard(textbox.value).
4) Push Button Object
- The PushButton object displays a button with text or an image, which calls a function when pressed.
button = PushButton(app, command=NameOfFunction)buttonis the variable name of the PushButton object;appis the variable name of the App object.NameOfFunctionis a custom function to run when we push the button.- Example:
from guizero import App, PushButton
def do_nothing():
print("Button was pressed")
app = App()
button = PushButton(app, command=do_nothing)
app.display()[Image: guizero window with a single "Button"]
- ⚠️ Name clash warning: guizero's
PushButton(on-screen) is different from gpiozero'sButton(physical). Don't mix them up when importing both libraries.
Example 6
- Connect an LED to GPIO22 and a resistor (
GPIO22 → LED → 330 Ω → GND). - Write a Python program to create two push buttons (GUI using guizero).
- ⭐ Pressing these buttons will turn the LED on/off.
[Image: Circuit schematic (GPIO22 → LED → 330Ω → GND) and breadboard photo]
- The Python code is below. More explanations: https://lawsie.github.io/guizero/pushbutton/
from gpiozero import LED
from guizero import App, PushButton
led = LED(22)
def start():
start_button.disable()
stop_button.enable()
led.on()
def stop():
start_button.enable()
stop_button.disable()
led.off()
app = App(width=100, height=150)
start_button = PushButton(app, command=start, text="On")
start_button.text_size = 30
stop_button = PushButton(app, command=stop, text="Off", enabled=False)
stop_button.text_size = 30
app.display()[Image: Resulting GUI — small window with large "On" (enabled) and "Off" (greyed out) buttons]
- How it works:
App(width=100, height=150)→ a small 100 × 150 window.start_button("On") → callsstart();stop_button("Off") → callsstop().enabled=False→ "Off" starts greyed out (LED is off initially, so nothing to turn off).- Pressing On: disables "On", enables "Off", turns the LED on.
- Pressing Off: enables "On", disables "Off", turns the LED off.
.text_size = 30→ makes button text bigger.
- A demonstration video is shown on the slide.
[Image: Demo video screenshot — Thonny running App_LED_OnOff.py with On/Off window]
Analogy Like an
elevator's call buttons — once you've pressed "On", that button is greyed outbecause pressing it again would do nothing. Only the useful action is available.
Example 7
- Connect an LED to GPIO22 and a resistor as in Example 6.
- Write a program to create a slider (GUI using guizero). Sliding it adjusts the brightness/intensity of the LED.
from gpiozero import PWMLED
from guizero import App, Slider
led = PWMLED(22)
def slider_changed(percent):
led.value = int(percent) / 100
app = App(title='PWM', width=500, height=150)
slider = Slider(app, command=slider_changed, width='fill', height=50)
slider.text_size = 30
app.display()[Image: Resulting GUI — window titled "PWM" with slider showing 20]
- More explanations: https://lawsie.github.io/guizero/slider/
- Key conversion: the slider gives 0–100, but
PWMLED.valueneeds 0–1:- e.g. slider at 20 →
led.value = 0.2→ LED at 20% brightness.
int(percent)converts the slider value to an integer before dividing.width='fill'makes the slider stretch across the whole window.- A demonstration video is shown on the slide.
[Image: Demo video screenshot — Thonny running App_LED_Slider.py with PWM window at 0]
Analogy This is literally a
dimmer switch on your screen: the slider is a percentage (like a volume bar 0–100), and dividing by 100 translates it into the LED's "language" (0.0–1.0).
5. Programming Raspberry Pi Towards IoT Applications Using Python
Introduction
- The Internet of Things (IoT) is the rapidly growing network of devices (things) connected to the internet.
- It does not just mean more computers using browsers, but actual appliances and wearable and portable technology.
- This includes all sorts of home automation — from smart appliances and lighting to security systems and even internet-operated pet feeders — as well as lots of less practical but fun projects.
- In this section, we study an example of how the Raspberry Pi can participate in the IoT using Python.
Example 8
- ⭐ Write a Python program to send a random integer to the ThingSpeak dashboard every one minute.
- No circuit connection is required.
- ⭐ However, we must set up a channel in ThingSpeak (as done in Lecture Note 5) and get its API Key.
- In ThingSpeak, create a new channel:
- Name: Lect8 – Ex8
- Field 1: Random Integer
- Other parameters left blank. Press Save Channel.
- Click the API Keys tab and record your ⭐ Write API Key for this channel.
[Image: ThingSpeak Channel Settings (Name: Lect8 - Ex8, Field 1: Random Integer) and API Keys tab showing Write API Key]
- ⚠️ The Raspberry Pi must be connected to the Internet.
- Running the code below sends a random integer (0–100) to ThingSpeak. The values appear on the graph in ThingSpeak.
- ⚠️ Put your own Write API Key.
import time, requests
from random import randint
PERIOD = 60 #seconds
BASE_URL = 'https://api.thingspeak.com/update.json'
KEY = 'Your Write API Key'
def send_data(Value):
data = {'api_key': KEY, 'field1': Value}
response = requests.post(BASE_URL, json=data)
while True:
Number = randint(0, 100)
print('Number: ' + str(Number))
send_data(Number)
time.sleep(PERIOD)[Image: ThingSpeak "Field 1 Chart" for Lect8 – Ex8 showing random integers plotted over time (15:01–15:07)]
- How it works:
randint(0, 100)→ random integer from 0 to 100 (inclusive of both ends).send_data()builds a JSON body{'api_key': ..., 'field1': ...}and sends an HTTP POST to ThingSpeak's update endpoint.time.sleep(60)→ waits 60 s, so one data point per minute.- Data rate:
- The Write API Key identifies which channel to write to and proves you're allowed to write there — keep it secret.
Analogy
ThingSpeak is a cloud notebook. The Write API Key is the key to your notebook's lock, field1 is the column you're writing in, and every minute the Pi writes one new number on the next line — ThingSpeak then draws the graph for you.