How to Use a Relay with a Raspberry Pi

Add an electrically-operated switch to your Pi!
John John (304)
20 minutes

A relay is an electrically-operated switch. These switches can be extremely useful for a variety of Raspberry Pi projects (think turning on a light or opening your garage door. Watch the video below to learn how to drive a relay using your Raspberry Pi.

Raspberry PiRaspberry Pi ×1
SainSmart 2-channel Relay Module ×1

Howchoo is reader-supported. As an Amazon Associate, we may earn a small affiliate commission at no cost to you when you buy through our links.

The following video will show you how to wire up the relay to your Raspberry Pi.

Watch the video:

Here's a copy of the test script used in the video:

#!/usr/bin/env python

import time

import RPi.GPIO as GPIO


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

time.sleep(0.25)

GPIO.output(17, GPIO.HIGH)
GPIO.cleanup()

To run the script, simply copy the code above to a file on your Raspberry Pi called test-relay.py (or whatever you want). And then run the script using:

python test-relay.py
We’re wrapping up 2021 with a list of Pi goodies that were worth the wait!
Ash Ash (354)
0

Nothing can slow down the Raspberry Pi Foundation, as even in 2021, the team managed to serve up a selection of new Raspberry Pi boards, modules, and fun accessories.