✦ VidyaVerseOpen interactive version

← Programming Concepts in Mechanical Engineering (25ME34I)

Raspberry Pi: Introduction, Setup and Motor Control

Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III

Read with diagrams, search and self-test

LEARNING OBJECTIVES

After studying this chapter you will be able to:

• Describe the Raspberry Pi hardware, model types and GPIO pins.

• Install Raspberry Pi OS, boot the Pi and set up network and remote access.

• Use breadboards, jumper wires, resistors and LEDs with GPIO pins safely.

• Program GPIO outputs and inputs using gpiozero and RPi.GPIO.

• Control the direction and speed of DC motors using the L298N driver and PWM.

• Build automated fan and water-pump controllers using relays.

8.1 What is a Raspberry Pi?

The Raspberry Pi is a low-cost, credit-card-sized single-board computer (SBC) developed by the Raspberry Pi Foundation (UK). It has a processor, RAM, USB ports, HDMI output, network connectivity and, most importantly for engineers, a row of GPIO (General Purpose Input/Output) pins through which it can read sensors and control LEDs, relays and motors. It runs a full Linux operating system (Raspberry Pi OS) and Python is pre-installed, which makes it ideal for automation, robotics, data acquisition and IoT projects.

Microcontroller vs Raspberry Pi: an Arduino is a microcontroller – it runs one program, has analog inputs and very precise timing but no operating system. A Raspberry Pi is a complete computer – it runs an OS, multitasks, connects to networks and displays, and is programmed in Python, but has no built-in analog input.

FeatureRaspberry PiArduino Uno
TypeSingle-board computerMicrocontroller board
Processor64-bit ARM, 1.5–2.4 GHz (quad-core)8-bit ATmega328P, 16 MHz
RAM1–16 GB2 KB
Operating systemRaspberry Pi OS (Linux)None
LanguagePython (also C, Java...)C/C++ (Arduino)
Analog inputNo (needs external ADC)6 channels, 10-bit
GPIO logic level3.3 V5 V
NetworkingWi-Fi, Bluetooth, EthernetNeeds add-on shield
Best forVision, data logging, networking, complex logicSimple real-time control

8.2 Raspberry Pi Models

ModelY e a rProcessorRAMNotes
Raspberry Pi 3 Model B+2 0 1 81.4 GHz quad-core Cortex-A531 GBWi-Fi, BT, common in labs
Raspberry Pi 4 Model B2 0 1 91.5–1.8 GHz quad-core Cortex-A721/2/4/ 8 GBUSB 3.0, dual micro-HDMI, USB-C power
Raspberry Pi 4002 0 2 0Pi 4 inside a keyboard4 GBDesktop computer form
Raspberry Pi Zero 2 W2 0 2 11 GHz quad-core512 MBVery small, low power
Raspberry Pi 52 0 2 32.4 GHz quad-core Cortex-A762/4/8/ 16 GBRP1 I/O chip, PCIe, power button
Raspberry Pi Pico2 0 2 1RP2040 microcontroller264 KBNot a computer; MicroPython

Fig. 8.1 Main parts of a Raspberry Pi 4/5 board

Main parts of the board:

• SoC (System on Chip): Broadcom processor containing CPU and GPU.

• RAM: working memory.

• microSD card slot: holds the operating system and files (acts as the hard disk).

• USB ports: keyboard, mouse, pen drive, camera.

• Ethernet port and Wi-Fi/Bluetooth: networking.

• micro-HDMI ports: connect monitors.

• USB-C power input: 5 V, 3 A (Pi 4) or 5 V, 5 A (Pi 5).

• CSI camera and DSI display connectors.

• 40-pin GPIO header: interface to the outside world.

8.3 GPIO Pins

The 40-pin header provides power pins, ground pins and 26 GPIO pins. Each GPIO pin can be programmed as a digital input (read a switch or sensor: HIGH/LOW) or a digital output (drive an LED, relay or motor driver: HIGH = 3.3 V, LOW = 0 V). Some pins also have special functions: PWM, I²C, SPI and UART.

Fig. 8.2 Raspberry Pi 40-pin GPIO header with BCM numbers

Pin numbering systems

• Physical (BOARD) numbering: pins are numbered 1 to 40 by their position on the header.

• BCM numbering: the Broadcom chip's GPIO numbers (GPIO17, GPIO18...). gpiozero always uses BCM numbers; RPi.GPIO lets you choose with GPIO.setmode(GPIO.BCM) or GPIO.setmode(GPIO.BOARD).

Example: physical pin 11 = GPIO17; physical pin 12 = GPIO18.

Pin functionPhysical pinsPurpose
3.3 V power1, 17Power sensors (low current)
5 V power2, 4Power 5 V modules (from supply)
Ground6, 9, 14, 20, 25, 30, 34, 39Common reference
I²C (SDA, SCL)3 (GPIO2), 5 (GPIO3)BMP180, LCD, ADC modules
SPI (MOSI, MISO, SCLK, CE0, CE1)19, 21, 23, 24, 26ADC MCP3008, displays
UART (TXD, RXD)8 (GPIO14), 10 (GPIO15)Serial communication, GPS
Hardware PWM12 (GPIO18), 32, 33, 35Motor speed, servo
SAFETY

GPIO pins work at 3.3 V. Never connect 5 V to a GPIO input – it can permanently damage the Pi. Each pin can safely supply only about 16 mA (50 mA total for all pins), so motors, pumps and relays must NEVER be connected directly; use a driver (L298N), a transistor or a relay module. Always switch off power before changing connections, and connect the grounds of all circuits together.

8.4 Setting up the Raspberry Pi

Hardware required

Raspberry Pi board, microSD card (16–32 GB, Class 10), official power supply (USB-C), HDMI monitor with micro-HDMI cable, USB keyboard and mouse, and internet (Wi-Fi or Ethernet). A case and heat sink/fan are recommended.

Installing the operating system (Raspberry Pi Imager)

1. On a PC, download and install Raspberry Pi Imager from raspberrypi.com/software.

2. Insert the microSD card into the PC using a card reader.

3. In Imager choose the device (Pi 4/Pi 5), the OS (Raspberry Pi OS 64-bit with desktop, or Lite for headless use) and the storage (SD card).

4. In OS customisation, set the hostname, username and password, Wi-Fi name and password, time zone and enable SSH.

5. Click Write; Imager downloads, writes and verifies the image.

6. Insert the card in the Pi, connect the monitor, keyboard and mouse, and connect power last. The Pi boots (red LED = power, green LED blinks = SD activity) and shows the desktop.

First-boot configuration and network setup

• Connect to Wi-Fi from the network icon on the taskbar, or plug in an Ethernet cable.

• Update the system from the terminal:

sudo apt update
sudo apt full-upgrade -y

• Open Preferences → Raspberry Pi Configuration → Interfaces (or run sudo raspi-config) and enable SSH, VNC, I²C, SPI as required.

• Find the IP address: hostname -I.

• Headless operation: from a laptop on the same network use ssh user@raspberrypi.local for a terminal or a VNC viewer for the desktop.

Useful Linux commands

CommandPurpose
pwd, ls, cd folderShow current folder, list files, change folder
mkdir projectsCreate a folder
nano blink.pyEdit a file in the terminal editor
python3 blink.pyRun a Python program
sudo reboot / sudo shutdown -h nowRestart / shut down safely
pinoutDisplay the GPIO pin diagram
i2cdetect -y 1List I²C devices connected
hostname -IShow IP address
N O T E

Always shut down with sudo shutdown -h now before removing power; pulling the plug can corrupt the SD card.

Python libraries for GPIO

• gpiozero – the officially recommended, beginner-friendly library, pre-installed on Raspberry Pi OS. It provides ready-made classes: LED, Button, Motor, Robot, OutputDevice, PWMOutputDevice, MotionSensor, DistanceSensor. It works on all models including Pi 5.

• RPi.GPIO – the older, widely used low-level library (setmode, setup, output, input, PWM). It works on Pi 3/4; on Pi 5 the new RP1 I/O chip is not supported by it, so the drop-in replacement package rpi-lgpio is installed instead and the same code runs unchanged.

Both styles are shown in this book because laboratory kits and exam papers use both.

8.5 Breadboard, Jumper Wires and Basic Circuits

A breadboard is a solderless board for building temporary circuits. In a full-size 830-point breadboard, the five holes of each numbered column (a–e, and f–j) are connected internally; the long rails on both sides marked + and − are connected along their length and are used for power and ground. A central gap separates the two halves so that ICs can straddle it.

Jumper wires (male-male, male-female, female-female) connect the Pi header to the breadboard. A resistor limits current; for an LED on a 3.3 V pin, 220–330 Ω gives about 5–10 mA. An LED is polarised: the long leg (anode, +) goes towards the GPIO through the resistor and the short leg (cathode, −) to ground.

Fig. 8.3 LED circuit on GPIO17

Program 8.1 – Blink an LED (first GPIO program)

# Program 8.1: Blink LED on GPIO17 using gpiozero
from gpiozero import LED
from time import sleep
led = LED(17)              # BCM pin 17 = physical pin 11
for i in range(5):
    led.on()
    print("LED ON")
    sleep(1)
    led.off()
    print("LED OFF")
    sleep(1)
OUTPUT
LED ON
LED OFF
LED ON
LED OFF
... (5 cycles)

The same program using RPi.GPIO:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)          # use BCM numbers
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.OUT)        # pin as output
try:
    for i in range(5):
        GPIO.output(17, GPIO.HIGH); time.sleep(1)
        GPIO.output(17, GPIO.LOW);  time.sleep(1)
finally:
    GPIO.cleanup()              # release pins safely

Program 8.2 – Push button input controlling an LED

The button is connected between GPIO2 (pin 3) and GND. gpiozero enables the internal pull-up resistor, so the pin reads HIGH normally and LOW when pressed.

from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(2)               # internal pull-up enabled
button.when_pressed = led.on
button.when_released = led.off
print("Press the button... (Ctrl+C to stop)")
pause()                          # keep program running

8.6 Pulse Width Modulation (PWM)

A GPIO pin is digital (ON/OFF). To vary the speed of a motor or the brightness of an LED, the pin is switched ON and OFF very rapidly. The fraction of time it is ON is the duty cycle:

Duty cycle = T_on / (T_on + T_off) × 100 %

Average voltage = Duty cycle × Supply voltage

A 12 V motor driven at 50 % duty cycle behaves as if supplied with about 6 V. Typical PWM frequency for DC motors: 100 Hz – 1 kHz.

# Program 8.3: LED brightness control with PWM
from gpiozero import PWMLED
from time import sleep
led = PWMLED(18)                    # hardware PWM pin
for duty in [0, 0.25, 0.5, 0.75, 1.0]:
    led.value = duty                # 0.0 to 1.0
    print(f"Duty cycle = {duty*100:.0f} %")
    sleep(1)
led.pulse()                         # smooth fade in and out
sleep(6)

8.7 Motor Driver Circuits: L298N

A Raspberry Pi pin gives a few milliamperes at 3.3 V, while a small DC gear motor needs 6–12 V and 200 mA–2 A. A motor driver amplifies the control signal. The L298N module contains a dual H-bridge IC that can drive two DC motors (or one stepper motor) up to 2 A each, from 5–35 V.

H-bridge principle: four switches arranged in an "H" around the motor. Closing one diagonal pair makes current flow one way (forward); closing the other pair reverses it (backward). Opening all stops the motor; shorting both terminals brakes it.

L298N pins

PinFunction
+12V (VS)Motor supply, 5–35 V (battery)
GNDCommon ground (connect to Pi GND)
+5V5 V logic output (when the 5 V regulator jumper is fitted and VS ≤ 12 V)
ENA, ENBEnable / speed (PWM) for motor A and B; remove jumper to use PWM
IN1, IN2Direction inputs for motor A
IN3, IN4Direction inputs for motor B
OUT1, OUT2 / OUT3, OUT4Motor A / motor B terminals

Direction truth table (motor A)

ENAIN1IN2Motor action
HIGH/PWMHIGHLOWForward (clockwise)
HIGH/PWMLOWHIGHReverse (anti-clockwise)
HIGHLOWLOWStop (coast)
HIGHHIGHHIGHBrake
LOWXXMotor off

Fig. 8.4 Wiring of Raspberry Pi, L298N and two DC motors

Connections used in this book: ENA → GPIO18 (pin 12), IN1 → GPIO23 (pin 16), IN2 → GPIO24 (pin 18), ENB → GPIO13 (pin 33), IN3 → GPIO5 (pin 29), IN4 → GPIO6 (pin 31), L298N GND → Pi GND (pin 6), 12 V battery → +12V and GND of L298N.

8.8 Practice: Motor Control and Automation (Week 8)

Program 8.4 – Control a DC motor with L298N (direction and speed) – gpiozero

# Program 8.4: DC motor control using L298N and gpiozero
from gpiozero import Motor
from time import sleep
motor = Motor(forward=23, backward=24, enable=18, pwm=True)
print("Forward at full speed"); motor.forward(1.0); sleep(3)
print("Forward at 50 % speed"); motor.forward(0.5); sleep(3)
print("Stop");                  motor.stop();       sleep(1)
print("Reverse at 75 % speed"); motor.backward(0.75); sleep(3)
print("Stop");                  motor.stop()
OUTPUT
Forward at full speed
Forward at 50 % speed
Stop
Reverse at 75 % speed
Stop

Program 8.5 – DC motor control with RPi.GPIO and PWM (SEE program)

# Program 8.5: L298N motor control using RPi.GPIO
import RPi.GPIO as GPIO
import time
ENA, IN1, IN2 = 18, 23, 24
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup([ENA, IN1, IN2], GPIO.OUT)
pwm = GPIO.PWM(ENA, 1000)       # 1 kHz PWM on ENA
pwm.start(0)                    # 0 % duty to begin
def forward(speed):
    GPIO.output(IN1, GPIO.HIGH)
    GPIO.output(IN2, GPIO.LOW)
    pwm.ChangeDutyCycle(speed)
def reverse(speed):
    GPIO.output(IN1, GPIO.LOW)
    GPIO.output(IN2, GPIO.HIGH)
    pwm.ChangeDutyCycle(speed)
def stop():
    GPIO.output(IN1, GPIO.LOW)
    GPIO.output(IN2, GPIO.LOW)
    pwm.ChangeDutyCycle(0)
try:
    for s in (40, 70, 100):     # ramp up speed
        print(f"Forward {s} %"); forward(s); time.sleep(2)
    stop(); print("Stop"); time.sleep(1)
    print("Reverse 60 %"); reverse(60); time.sleep(3)
    stop(); print("Stop")
except KeyboardInterrupt:
    print("Interrupted by user")
finally:
    pwm.stop()
    GPIO.cleanup()              # always release the pins
OUTPUT
Forward 40 %
Forward 70 %
Forward 100 %
Stop
Reverse 60 %
Stop

Explanation: IN1/IN2 set the direction (truth table), the PWM duty cycle on ENA sets the speed, and finally ensures the motor stops and pins are released even if Ctrl+C is pressed.

Program 8.6 – Keyboard-controlled motor (interactive)

from gpiozero import Motor
motor = Motor(forward=23, backward=24, enable=18)
while True:
    cmd = input("f=forward b=back s=stop q=quit, speed% : ")
    parts = cmd.split()
    if not parts:
        continue
    speed = int(parts[1]) / 100 if len(parts) > 1 else 1.0
    if parts[0] == "f":
        motor.forward(speed)
    elif parts[0] == "b":
        motor.backward(speed)
    elif parts[0] == "s":
        motor.stop()
    elif parts[0] == "q":
        motor.stop(); break

Relays for AC loads

A relay is an electrically operated switch. A small current through its coil (driven by a transistor on the relay module) closes contacts that can switch a large AC/DC load such as a 230 V pump or fan. The relay provides electrical isolation between the Pi and the mains. Relay modules have terminals IN, VCC, GND on the control side and COM, NO (normally open), NC (normally closed) on the load side. Many modules are active-LOW: the relay turns ON when IN is LOW.

Fig. 8.5 Automated pump / fan controller

SAFETY

230 V AC wiring must be done only by a qualified person with insulated terminals and an enclosure. For laboratory practice use a 12 V DC pump or fan.

Program 8.7 – Automated temperature-controlled fan

The fan (through a relay on GPIO17) switches ON when the temperature exceeds 30 °C and OFF below 28 °C. The 2 °C gap, called hysteresis, prevents rapid ON/OFF "chattering" near the set point. The DHT11 sensor is explained in Chapter 9.

# Program 8.7: Automatic fan controller with hysteresis
import time, board, adafruit_dht
from gpiozero import OutputDevice
fan = OutputDevice(17, active_high=False, initial_value=False)
dht = adafruit_dht.DHT11(board.D4)
ON_TEMP, OFF_TEMP = 30.0, 28.0
while True:
    try:
        t = dht.temperature
        if t is not None:
            if t >= ON_TEMP and not fan.value:
                fan.on()
            elif t <= OFF_TEMP and fan.value:
                fan.off()
            state = "ON" if fan.value else "OFF"
            print(f"Temp = {t:.1f} °C   Fan {state}")
    except RuntimeError:
        pass                    # DHT read glitch, try again
    time.sleep(2)
OUTPUT
Temp = 27.0 °C   Fan OFF
Temp = 29.0 °C   Fan OFF
Temp = 30.0 °C   Fan ON
Temp = 29.0 °C   Fan ON
Temp = 28.0 °C   Fan OFF

Program 8.8 – Automated water-pump controller (SEE program)

A tank has two float switches: LOW level on GPIO22 and HIGH (full) level on GPIO27, wired to ground (closed when the float is up/submerged). The pump relay is on GPIO17. Logic: start the pump when the water falls below the low float; stop it when the high float is reached.

# Program 8.8: Automatic water pump controller
from gpiozero import Button, OutputDevice
from time import sleep
low_float = Button(22)     # pressed = water above LOW mark
high_float = Button(27)    # pressed = water reached FULL mark
pump = OutputDevice(17, active_high=False, initial_value=False)
print("Pump controller running (Ctrl+C to stop)")
try:
    while True:
        if not low_float.is_pressed and not pump.value:
            pump.on()
            print("Level LOW  -> Pump ON")
        elif high_float.is_pressed and pump.value:
            pump.off()
            print("Tank FULL  -> Pump OFF")
        sleep(0.5)
except KeyboardInterrupt:
    pump.off()
    print("Controller stopped, pump OFF")
OUTPUT
Pump controller running (Ctrl+C to stop)
Level LOW  -> Pump ON
Tank FULL  -> Pump OFF
Level LOW  -> Pump ON
Tank FULL  -> Pump OFF
Controller stopped, pump OFF

Simulation without hardware. The control logic can be tested on any PC by replacing sensors with a simple model:

# Simulating the pump controller logic on a PC
level, pump = 30, False          # percent, pump state
LOW, HIGH = 20, 90
for minute in range(0, 60, 5):
    if level <= LOW and not pump:
        pump = True
        print(f"t={minute:2d} min level {level}% PUMP ON")
    elif level >= HIGH and pump:
        pump = False
        print(f"t={minute:2d} min level {level}% PUMP OFF")
    level += 12 if pump else -4  # filling vs consumption
OUTPUT
t=15 min level 18% PUMP ON
t=45 min level 90% PUMP OFF

8.9 Solved Exam Questions

Q1. Give an overview of Raspberry Pi hardware and model types. (6 marks)

Answer: The Raspberry Pi is a credit-card-sized single-board computer with an ARM SoC, 1–16 GB RAM, microSD storage, USB, HDMI, Ethernet, Wi-Fi/Bluetooth, camera/display connectors and a 40-pin GPIO header. It runs Raspberry Pi OS with Python pre-installed. Models: Pi 3B+, Pi 4B (up to 8 GB, USB 3), Pi 400, Zero 2 W, Pi 5 (2.4 GHz, RP1 I/O chip) and the Pico microcontroller. See Sections 8.1–8.2.

Q2. Explain the GPIO pins of the Raspberry Pi. (6 marks)

Answer: The header has 40 pins: 3.3 V (pins 1, 17), 5 V (2, 4), eight ground pins and 26 GPIO pins. A GPIO pin can be set as input (reads HIGH/LOW from switches and sensors) or output (drives LEDs, relays, driver inputs at 3.3 V). Special functions: PWM (GPIO12, 13, 18, 19), I²C (GPIO2/3), SPI and UART. Two numbering schemes: BCM and BOARD. Precautions: 3.3 V logic only, about 16 mA per pin, no direct motor connection.

Q3. Explain the steps to set up a Raspberry Pi. (6 marks)

Answer: Write Raspberry Pi OS to a microSD card using Raspberry Pi Imager (set user, Wi-Fi, SSH in customisation); insert card; connect monitor, keyboard, mouse; apply power; complete first-boot setup; connect to network; update with sudo apt update && sudo apt full-upgrade; enable interfaces (SSH, VNC, I²C, SPI) with raspi-config; note IP with hostname -I for remote access.

Q4. Write a program to control a DC motor using the L298N motor driver with Raspberry Pi. (20 marks, SEE)

Answer: Wiring as in Fig. 8.4 and the truth table of Section 8.7. Program 8.5 (RPi.GPIO with PWM) or Program 8.4 (gpiozero). Explain direction control through IN1/IN2, speed through PWM on ENA and safe cleanup in finally.

Q5. Write a program to build an automated water-pump controller using Raspberry Pi. (20 marks, SEE)

Answer: Block diagram Fig. 8.5; float switches on GPIO22/27; relay on GPIO17; Program 8.8 with explanation of the start/stop logic and the simulated version.

Q6. What is PWM? How is it used to control motor speed?

Answer: Pulse Width Modulation switches a digital output ON and OFF at a fixed frequency while varying the ON time. The average voltage, and therefore the motor speed, is proportional to the duty cycle. In RPi.GPIO: pwm = GPIO.PWM(pin, 1000); pwm.start(0); pwm.ChangeDutyCycle(60).

8.10 Multiple Choice Questions

1. Raspberry Pi is a a) microcontroller b) single-board computer c) PLC d) motor driver

Answer: (b) Reason: It is a complete computer on one board running a Linux OS.

2. The logic level of Raspberry Pi GPIO pins is a)5V b)3.3V c) 12 V d) 1.8 V

Answer: (b) Reason: Applying 5 V to a GPIO input can damage the processor.

3. How many pins are on the Raspberry Pi GPIO header (Pi 2 onwards)? a) 26 b) 40 c) 28 d) 20

Answer: (b) Reason: Models from the B+ onwards have a 40-pin header.

4. Physical pin 11 corresponds to BCM a) GPIO11 b) GPIO17 c) GPIO18 d) GPIO27

Answer: (b) Reason: BOARD pin 11 is GPIO17 in BCM numbering.

5. The recommended beginner GPIO library on Raspberry Pi OS is a) gpiozero b) pygame c) numpy d) tkinter

Answer: (a) Reason: gpiozero is pre-installed, simple and works on all models including Pi 5.

6. The L298N module is a a) temperature sensor b) dual H-bridge motor driver c) relay d) voltage regulator only

Answer: (b) Reason: It contains two H-bridges to control two DC motors in both directions.

7. With ENA HIGH, IN1 = HIGH and IN2 = LOW, motor A a) rotates forward b) rotates reverse c) brakes d) is disconnected

Answer: (a) Reason: One diagonal of the H-bridge conducts, giving forward rotation.

8. The speed of a DC motor through L298N is controlled by applying PWM to a) IN1 b) ENA c) GND d) +12V

Answer: (b) Reason: ENA enables the bridge; the PWM duty cycle on it sets the average voltage.

9. A 12 V motor supply at 25 % duty cycle gives an average voltage of a)3V b)6V c)9V d)12V

Answer: (a) Reason: 0.25 × 12 V = 3 V.

10. Which tool is used to write Raspberry Pi OS to an SD card? a) Raspberry Pi Imager b) Notepad c) PyCharm d) Excel

Answer: (a) Reason: Raspberry Pi Imager downloads and writes the OS image and allows customisation.

11. GPIO.cleanup() is used to a) delete files b) reset GPIO pins used by the program c) clean the SD card d) restart the Pi

Answer: (b) Reason: It returns pins to input mode, protecting hardware after the program ends.

12. A relay module is used with Raspberry Pi to a) measure temperature b) switch high-power loads with isolation c) generate PWM d) store data

Answer: (b) Reason: The relay contacts switch pumps/fans while isolating the Pi from the load circuit.

13. Which command enables I²C and SSH from the terminal? a) sudo raspi-config b) pip install c) ls -l d) python3

Answer: (a) Reason: raspi-config has an Interfaces menu to enable SSH, I²C, SPI, VNC.

14. The long leg of an LED is the a) cathode b) anode c) ground d) gate

Answer: (b) Reason: The anode (+) is longer and connects towards the positive supply/GPIO.

15. Why must a motor not be connected directly to a GPIO pin? a) Motors need AC b) GPIO current is only a few mA and back-EMF can damage the Pi c) GPIO gives 12 V d) It is allowed

Answer: (b) Reason: Motors draw hundreds of mA and generate voltage spikes; a driver is required.

16. On Raspberry Pi 5, existing RPi.GPIO programs can run after installing a) rpi-lgpio b) pandas c) opencv d) nothing

Answer: (a) Reason: Pi 5's RP1 chip is not supported by RPi.GPIO; rpi-lgpio provides the same API.

8.11 Exercises

1. Write a program to make a traffic-light sequence with red, yellow and green LEDs.

2. Write a program to run a motor forward for 5 s, stop 2 s, reverse 5 s, repeated 3 times.

3. Modify Program 8.7 so that the fan speed (PWM) increases in steps with temperature.

4. Draw the wiring diagram for controlling two motors of a robot car using L298N.

5. Explain the precautions to be taken while working with Raspberry Pi GPIO.