Controlling Relay Boards using RaspberryPi

This post is intended to help beginners to interface Relay boards with Raspberry Pi. Relay boards are used for various isolation applications including home automation, automotive etc.



Below is the connection diagram for interfacing 4 channel relay which can be purchased from this link. Similar connections are applicable to 8-channel, 2- channel and 1-channel Relay boards with a few changes in the firmware shown in this post.




Note: Below code uses the BCM processor number as shown.



Write a python script as below and save it as

import RPi.GPIO as GPIO
from time import sleep

# The script as below using BCM GPIO 00..nn numbers

# Set relay pins as output
GPIO.setup(18, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)

while (True):
    # Turn all relays ON
    GPIO.output(18, GPIO.HIGH)
    GPIO.output(23, GPIO.HIGH)
    GPIO.output(24, GPIO.HIGH)
    GPIO.output(25, GPIO.HIGH)
    # Sleep for 5 seconds
    # Turn all relays OFF
    GPIO.output(18, GPIO.LOW)
    GPIO.output(23, GPIO.LOW)
    GPIO.output(24, GPIO.LOW)
    GPIO.output(25, GPIO.LOW)   
    # Sleep for 5 seconds

Run the code as sudo python

The code example can be downloaded from our Github channel

8 thoughts on “Controlling Relay Boards using RaspberryPi

  1. Pingback: Hydroponics system controlled by Raspberry Pi an overview | Sony Arouje Blog

  2. hi there,
    is it best to supply power to relay board with separate power supply? reason I ask is I just saw a relay board with power supplied directly from the raspberry pi and I’m a little confused. which is the best way?

    • That depends on the type of relay. If you are using a 5V relay you may get the necessary supply source from the RPi header itself. But its better to use another power supply for the relay board for avoiding odd behaviour at the supply voltage when relay is switching fast.

  3. Pingback: 极客DIY:轻松使用树莓派控制灯-遛马网

  4. is it possible to power up home appliances through the relay board? i want to connect wall sockets to the screws is it possible? Thank you

  5. hello when I am connecting ground pin of 2 channel relay 5v to ground pin of raspberry pi 3 the pi is turning off can you tell me how to solve this problem I have 2 channel relay

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s