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 relay_control.py
import RPi.GPIO as GPIO
from time import sleep
# The script as below using BCM GPIO 00..nn numbers
GPIO.setmode(GPIO.BCM)
# 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
sleep(5)
# 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
sleep(5)
Run the code as sudo python relay_control.py
The code example can be downloaded from our Github channel
Pingback: Hydroponics system controlled by Raspberry Pi an overview | Sony Arouje Blog
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?
Thanks
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.
Pingback: 极客DIY:轻松使用树莓派控制灯-遛马网
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
Yes, it is possible to control the appliances having maximum current rating as that of the relay used.
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
In normal case, there should not be any issue. Please check whether your Relay board is having any short circuit problem between VCC and GND pins.