ABC of Electronics cosycom.com
RASPBERRY PI 17 · Outputs

Driving a Relay from the Raspberry Pi

The same transistor-and-relay isolation from Lesson cb-11, wired to a 3.3V-logic GPIO pin instead of a manual control signal or an Uno pin.

You'll need: the full transistor-and-relay circuit from Lesson cb-11 (flyback diode included), or a pre-built relay module board (common and inexpensive, with the transistor and diode already on the board — check its documentation for whether it needs 3.3V or 5V logic to trigger).

The core safety principle from Lesson cb-11 and Lesson ard-14 carries over unchanged: never connect a relay coil directly to a GPIO pin. The one Pi-specific detail to check carefully is logic level — Lesson rpi-08 already flagged that Pi GPIO pins are 3.3V and not 5V-tolerant, and many off-the-shelf relay modules are designed expecting a 5V trigger signal. Check your specific module's documentation; some work fine at 3.3V, others need a small logic-level shifter, and connecting a Pi GPIO pin to a module that expects 5V logic and pulls current backward into the pin risks damaging it.

relay.py
import RPi.GPIO as GPIO
import time

RELAY_PIN = 23

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

try:
    GPIO.output(RELAY_PIN, GPIO.HIGH)
    time.sleep(2)
    GPIO.output(RELAY_PIN, GPIO.LOW)
finally:
    GPIO.cleanup()

This code is deliberately almost identical to Lesson rpi-09's blink script — driving a relay module in code is no different from driving an LED, since the module's own onboard circuitry handles the actual isolation and switching for you. As always with relay-controlled loads, keep anything the contacts switch to low DC voltage for practice builds.

Pi GPIO23 Relay modulecheck logic voltage! Switched loadabcofelectronics
A pre-built relay module handles the transistor and flyback diode internally — but always confirm its trigger voltage matches the Pi's 3.3V logic.
TRY THIS
Before wiring any relay module to a Pi, check its documentation for trigger voltage — many are built expecting 5V logic and may need a level shifter to work safely with the Pi's 3.3V GPIO.