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